python進階學習chapter02(列表、字典、集合操作)

來源:互聯網
上載者:User

標籤:對象   http   ESS   有一個   數字   執行個體   mes   data   索引值   

  1. 如何在列表、字典、集合中篩選資料
  2. 列表(元組)的重新命名
  3. 詞頻統計的實現
  4. 字典的排序
  5. 尋找多個字典的公用鍵
  6. 如何讓字典保持有序
  7. 如何保持曆史紀錄(使用deque隊列)

 

一、如何在列表、字典、集合中篩選資料

  問題引入:

列表:[-10,2,2,3,-2,7,6,9] 找出所有的非負數

字典:{1:90,2:55,3:87...} 找出所有值大於60的索引值對

集合:{2,3,8,6,7,5} 找出所有被3整除的數

 列表:

#方法一,迭代data=[1,5,-4,-6,0,7,9]res=[]for num in data:    if num >=0:        res.append(num)print(res)#方法二,過濾函數filterres1=filter(lambda x:x>0,data)print(list(res1))#方法三,清單產生器[x for x in data if x >= 0]  

 字典:

#字典students={x:randint(30,100) for x in range(1,21)}print(students)#篩選處成績80分以上的,items()會同時遍曆鍵和值res4={k:v for k,v in students.items() if v>=90}print(res4)

集合:

#集合set=set(data)res5={x for x in set if x%2==0}print(res5)

二、列表(元組)的重新命名

問題引入:

1 = (‘sun‘,‘25‘,‘girl‘,‘[email protected]‘)print(s1[0])

使用數字作為數組的索引,讀取的時候可讀性太差了,可以改一下命名

NAME=0AGE=1SEX=2EMAIL=3print(s1[AGE])

或者匯入namedtuple

from collections import namedtuplestudents=namedtuple(‘Student‘,[‘name‘,‘age‘,‘sex‘,‘email‘])#定義一個類s2=students(‘sun‘,‘25‘,‘girl‘,‘[email protected]‘)#執行個體化一個類print(type(s2))print(s2.email)#相當於調用執行個體的屬性

三、詞頻統計的實現

問題引入:

[6, 7, 5, 9, 4, 1, 8, 6, 2, 9]

希望統計各個元素出現的次數,可以看作一個詞頻統計的問題。

我們希望最終得到一個這樣的結果:{6:2, 7:1...}即 {某個元素:出現的次數...}

#方法一list=[randint(1,10) for x in range(10)]print(list)d=dict.fromkeys(list,0)for x in list:    d[x]+=1print(d)#方法二from collections import Counterd1=Counter(list)print(d1)print(d1.most_common(3))

dict.fromkeys()方法是用於建立一個新字典,傳入兩個參數,序列和初始值。http://www.runoob.com/python/att-dictionary-fromkeys.html

collections的Counter 模組見下一篇介紹

四、字典的排序

問題引入:

python字典本身是無序的,每一次訪問的順序都是隨機的。我們可以通過使用sorted對字典排序,但是sorted函數僅僅是對字典的鍵進行排序,沒有考慮值

那如果需要對下面這個字典按值排序呢?{‘Tom‘: 87, ‘Jack‘: 90, ‘Rose‘: 100.....}

方法一,使用zip函數將字典的每一對(值,鍵)打包成元組,再用sorted排序。zip函數:http://www.runoob.com/python/python-func-zip.html

dict={x:randint(60,100) for x in ‘abcdef‘}print(dict)print(sorted(zip(dict.values(),dict.keys())))

 方法二,sorted函數本身是可以傳入一個key的,然後可以按照這個指定的key排序,sorted函數還是很強大的,http://www.runoob.com/python/python-func-sorted.html

students = [(‘john‘, ‘A‘, 15), (‘jane‘, ‘B‘, 12), (‘dave‘, ‘B‘, 10)]>>> sorted(students, key=lambda s: s[2])            # 按年齡排序[(‘dave‘, ‘B‘, 10), (‘jane‘, ‘B‘, 12), (‘john‘, ‘A‘, 15)]

  

五、尋找多個字典的公用鍵

問題引入:如何尋找三場比賽中,每場都有進球的球員呢

先產生類比資料:

from random import randint,sample
s1 = {x: randint(1,3) for x in sample(‘abcdef‘, randint(3, 6))}
s2 = {x: randint(1,3) for x in sample(‘abcdef‘, randint(3, 6))}
s3 = {x: randint(1,3) for x in sample(‘abcdef‘, randint(3, 6))}

{‘c‘: 1, ‘e‘: 3, ‘b‘: 1}
{‘c‘: 3, ‘d‘: 1, ‘b‘: 2}
{‘e‘: 3, ‘a‘: 2, ‘f‘: 2, ‘b‘: 1}

 方法一,遍曆

res=[]
for x in s1:
if x in s2 and x in s3:
res.append(x)
print(res)

[‘b‘]

 方法二,與運算

print(s1.keys()&s2.keys()&s3.keys())

 方法三,使用map和reduce。map和reduce的用法之後文章單獨介紹

>>> map(dict.viewkeys, [s1, s2, s3])[dict_keys([‘a‘, ‘b‘, ‘f‘]), dict_keys([‘a‘, ‘b‘, ‘e‘, ‘d‘, ‘g‘, ‘f‘]), dict_keys([‘a‘, ‘b‘, ‘e‘, ‘d‘, ‘f‘])]>>> reduce(lambda x,y: x&y, map(dict.viewkeys, [s1, s2, s3]))set([‘a‘, ‘b‘, ‘f‘]) 

五、如何讓字典保持有序

字典本身是無序的,如果需要在訪問的時候保持是錄入時候的順序,可以使用collections的OrderedDict

from collections import OrderedDictd=OrderedDict()d[‘sun‘]=(1,35)d[‘yue‘]=(2,37)d[‘ru‘]=(3,40)for i in d:    print(i)sunyueru

  

六、儲存記錄(使用deque隊列)

如何儲存一個猜數字遊戲中你已經猜過的數字呢

先看一下沒有儲存的猜數字遊戲的版本:

from collections import dequefrom random import randintN = randint(0, 100)def guess(k):    if k == N:        print "right"        return True    if k < N:        print "%s is less-than N" % k    if k > N:        print "%s is greater-than N" % k    return Falsewhile True:    line = raw_input("please input a number:")    if line.isdigit():        k = int(line)            if guess(k):            break  

  如果將每次猜的數字都存放在隊列中,如果使用者輸入history就輸出猜過的數字,版本二:

from collections import dequefrom random import randintN = randint(0, 100)history = deque([], 5)def guess(k):    if k == N:        print "right"        return True    if k < N:        print "%s is less-than N" % k    if k > N:        print "%s is greater-than N" % k    return Falsewhile True:    line = raw_input("please input a number:")    if line.isdigit():        k = int(line)        history.append(k)        if guess(k):            break    elif line == "history" or line == "h?":        print list(history)

  如果還需把這個隊列儲存下來,下次重新執行程式的時候還可以用呢,可以使用pickle模組

先儲存

>>> import pickle>>> s = [1, 2, 3, 4, 5]>>> pickle.dump(s, open(‘object‘, ‘w‘))>>> # 這樣就將s對象存在了object這個檔案中,並且這個檔案有一個寫入權限

下次可以讀

>>> import pickle>>> s = pickle.load(‘object‘)>>> s[1, 2, 3, 4, 5]

  

python進階學習chapter02(列表、字典、集合操作)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.