Python進(jìn)階強(qiáng)化訓(xùn)練之?dāng)?shù)據(jù)結(jié)構(gòu)與算法進(jìn)階_第1頁
Python進(jìn)階強(qiáng)化訓(xùn)練之?dāng)?shù)據(jù)結(jié)構(gòu)與算法進(jìn)階_第2頁
Python進(jìn)階強(qiáng)化訓(xùn)練之?dāng)?shù)據(jù)結(jié)構(gòu)與算法進(jìn)階_第3頁
Python進(jìn)階強(qiáng)化訓(xùn)練之?dāng)?shù)據(jù)結(jié)構(gòu)與算法進(jìn)階_第4頁
Python進(jìn)階強(qiáng)化訓(xùn)練之?dāng)?shù)據(jù)結(jié)構(gòu)與算法進(jìn)階_第5頁
已閱讀5頁,還剩10頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

1、Python進(jìn)階強(qiáng)化訓(xùn)練之?dāng)?shù)據(jù)結(jié)構(gòu)與算法進(jìn)階如何在列表、字典、集合中根據(jù)條件篩選數(shù)據(jù)?實(shí)際問題1. 過濾列表中的負(fù)數(shù)2. 篩選出字典種值高于90的項(xiàng)3. 篩選出集合種能被3整出的元素圍繞上面三個(gè)問題我們來進(jìn)行討論,比如下面有一個(gè)列表:>>> from random import randint>>> li = randint(-10, 10) for _ in range(10)>>> li-10, -9, 1, 10, -3, -7, -6, -7, 4, -5我們常規(guī)的做法就是通過for循環(huán)對列表中的每一個(gè)值進(jìn)行迭代,然后判斷如果值大于

2、等于0,就確定這個(gè)值是一個(gè)整數(shù),否則就丟棄,比如下面的代碼:>>> result = >>> for n in li:# 如果這個(gè)元素大于等于0. if n >= 0:# 加入的result列表中. result.append(n).>>> result1, 10, 4實(shí)例本篇所有的代碼均在Python 3.5.x種運(yùn)行,如果你使用的是python 2.7.x,那么請自行測試,在此之前,請導(dǎo)入一下模塊用于測試:# 用于生成隨機(jī)數(shù)>>> from random import randint# 準(zhǔn)確測量小段代碼的執(zhí)行時(shí)間

3、>>> import timeit請仔細(xì)閱讀下面的代碼,看完后你將會(huì)有不一樣的收獲。列表· filter函數(shù)生成一個(gè)隨機(jī)列表>>> li = randint(-10, 10) for _ in range(10)>>> li6, -8, 9, 3, 3, 8, 9, -4, 9, -6# x=列表中的一個(gè)元素,有多少個(gè)元素就迭代多少次>>> result = filter(lambda x: x >=0, li)>>> for n in result:. print(n).6933899&

4、#183; 列表解析生成一個(gè)隨機(jī)列表>>> li = randint(-10, 10) for _ in range(10)>>> li8, -5, -2, 8, 9, 4, -6, -5, 5, 4>>> x for x in li if x >=0 8, 8, 9, 4, 5, 4· filter與列表解析性能對比使用filter執(zhí)行時(shí)間>>> timeit.Timer('filter(lambda x: x >=0, 4, -1, 1, 3, -10, 5, -8, 0, 6, 3)&#

5、39;).timeit()0.38938787838583266使用列表解析執(zhí)行時(shí)間>>> timeit.Timer('x for x in 4, -1, 1, 3, -10, 5, -8, 0, 6, 3 if x >=0 ').timeit()1.1142896312373978通過以上的測試可以看出filter的執(zhí)行時(shí)間明顯比列表解析要快些,當(dāng)然這并不是一個(gè)非常準(zhǔn)確的數(shù)字,還是有待考察的。字典先隨機(jī)生成一個(gè)字典:>>> dic = x: randint(60, 100) for x in range(1, 21) >>

6、> dic1: 61, 2: 75, 3: 69, 4: 70, 5: 79, 6: 90, 7: 74, 8: 85, 9: 77, 10: 86, 11: 93, 12: 96, 13: 86, 14: 79, 15: 60, 16: 84, 17: 70, 18: 72, 19: 61, 20: 87· 字典解析>>> k: v for k, v in dic.items() if v > 90 11: 93, 12: 96集合生成一個(gè)集合:>>> li = randint(-10, 10) for _ in range(10)&

7、gt;>> s = set(li)>>> s0, 1, 3, 4, 7, -9, -8· 集合解析>>> x for x in s if x % 3 = 0 0, 3, -9如何為元組中的每個(gè)元素命名、提高程序可讀性?實(shí)際問題某校的學(xué)生信息系統(tǒng)中的數(shù)據(jù)存儲(chǔ)格式如下:(名字,年齡,性別,郵箱地址)比如有如下學(xué)生信息:student1 = ('Hello', 15, 'Schoolboy', 'hello')student2 = ('World', 16, 'Girls

8、', 'World')student3 = ('ansheng', 20, 'Schoolboy', '').通常我們會(huì)以如下方式進(jìn)行取值:>>> student12'Schoolboy'>>> student13'hello'在代碼比較多的情況下,使用大量的索引進(jìn)行訪問會(huì)降低程序的可讀性,如何解決這個(gè)問題呢?方案1定義類似于其他語言的枚舉類型,也就是定義一系列的數(shù)值常量.# 創(chuàng)建一個(gè)學(xué)生>>> student = ('anshe

9、ng', 20, 'Schoolboy', '')# 定義常量>>> NAME, AGE, SEX, EMAIL = range(4)# 通過常量進(jìn)行取值>>> studentNAME'ansheng'>>> studentAGE20>>> studentEMAIL''方案2使用標(biāo)準(zhǔn)庫中的dtuple替代內(nèi)置的tuple>>> from collections import namedtuple>

10、>> Student = namedtuple('Student', 'name','age','sex','email')>>> s = Student('ansheng', 20, 'Schoolboy', '')>>> sStudent(name='ansheng', age=20, sex='Schoolboy', email='')# 使用屬性進(jìn)行訪問>&g

11、t;> 'ansheng'>>> s.age20>>> s.sex'Schoolboy's是tuple的一個(gè)子類>>> isinstance(s, tuple)True如何統(tǒng)計(jì)序列中元素的出現(xiàn)頻度?實(shí)際問題1. 某隨機(jī)的列表中,找出出現(xiàn)次數(shù)最高的三個(gè)元素,他們的出現(xiàn)次數(shù)是多少?2. 對某英文文章的單詞進(jìn)行詞頻統(tǒng)計(jì),找出出現(xiàn)次數(shù)最高的10個(gè)單詞,他們出現(xiàn)的次數(shù)是多少?解決方案使用collections.Counter對象,將序列傳入Counter的構(gòu)造器,得到Counter對象是元素頻度的字典

12、,Counter.most_common(n)方法得到頻度最高的n個(gè)元素的列表實(shí)例· 常規(guī)的解決方法生成隨機(jī)序列的列表>>> from random import randint>>> li = randint(0, 20) for _ in range(30)>>> li14, 11, 10, 13, 19, 10, 3, 17, 12, 13, 18, 5, 10, 1, 9, 17, 1, 8, 3, 15, 8, 3, 20, 10, 9, 20, 6, 13, 8, 20以字典的形式創(chuàng)建每個(gè)數(shù)字出現(xiàn)的次數(shù),# 默認(rèn)的出現(xiàn)

13、次數(shù)為0>>> count = dict.fromkeys(li, 0)>>> count1: 0, 3: 0, 5: 0, 6: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 17: 0, 18: 0, 19: 0, 20: 0每遇到一個(gè)x(列表中的數(shù)),就去字典中讓值+1>>> for x in li:. countx += 1.>>> count1: 2, 3: 3, 5: 1, 6: 1, 8: 3, 9: 2, 10: 4, 11: 1, 12:

14、 1, 13: 3, 14: 1, 15: 1, 17: 2, 18: 1, 19: 1, 20: 3然后循環(huán)count找到最大的三個(gè)數(shù)字,取出來就好。· 使用collections.Counter對象# 導(dǎo)入Counter>>> from collections import Counter>>> count = Counter(li)>>> countCounter(10: 4, 3: 3, 8: 3, 13: 3, 20: 3, 1: 2, 9: 2, 17: 2, 5: 1, 6: 1, 11: 1, 12: 1, 14:

15、 1, 15: 1, 18: 1, 19: 1)>>> count.most_common(3)(10, 4), (3, 3), (8, 3)· 英文文章詞頻統(tǒng)計(jì)實(shí)例>>> from collections import Counter>>> import re>>> txt = open('jquery.cookie.js').read()>>> count = Counter(re.split('W+', txt)>>> countCount

16、er('s': 20, 'cookie': 18, 'options': 16, 'value': 12, 'function': 11, 'key': 10, 'var': 10, 'return': 9, 'expires': 8, 'if': 8, 'config': 8, 't': 6, 'result': 5, 'the': 5, 'a': 5,

17、'it': 5, '1': 4, 'decode': 4, 'i': 4, 'converter': 4, 'factory': 4, 'undefined': 4, 'cookies': 4, 'read': 3, 'domain': 3, 'g': 3, 'encode': 3, 'raw': 3, 'path': 3, 'name': 3, '

18、replace': 3, 'typeof': 3, 'parts': 3, 'we': 3, 'define': 3, 'document': 3, 'is': 3, 'pluses': 3, 'jquery': 3, 'If': 3, '': 2, 'else': 2, 'for': 2, 'object': 2, 'can': 2, 'json'

19、: 2, 'join': 2, 'days': 2, 'not': 2, 'jQuery': 2, 'in': 2, 'l': 2, 'parse': 2, 'ignore': 2, 'split': 2, 'isFunction': 2, 'unusable': 2, 'stringifyCookieValue': 2, 'secure': 2, 'extend': 2,

20、 'decodeURIComponent': 2, 'parseCookieValue': 2, 'JSON': 2, '0': 2, 'defaults': 2, 'extending': 1, 'storing': 1, 'Copyright': 1, 'thus': 1, 'use': 1, 'place': 1, 'require': 1, 'max': 1, 'lengt

21、h': 1, 'according': 1, 'AMD': 1, 'carhartl': 1, 'first': 1, 'globals': 1, 'catch': 1, 'https': 1, 'are': 1, 'try': 1, 'Write': 1, 'spaces': 1, 'written': 1, 'array': 1, 'age': 1, '

22、supported': 1, 'attribute': 1, 'under': 1, 'exports': 1, 'that': 1, 'Klaus': 1, 'RFC2068': 1, 'Replace': 1, 'as': 1, 'shift': 1, 'Prevent': 1, '864e': 1, 'slice': 1, 'prevents': 1, 'string

23、ify': 1, 'loop': 1, 'e': 1, 'at': 1, 'v1': 1, '5': 1, 'com': 1, 'when': 1, 'toUTCString': 1, 'setTime': 1, 'CommonJS': 1, 'false': 1, 'amd': 1, 'Plugin': 1, 'quoted': 1, 'couldn

24、9;: 1, 'an': 1, 'no': 1, 'github': 1, 'argument': 1, 'Must': 1, 'license': 1, 'second': 1, 'break': 1, 'Browser': 1, 'IE': 1, 'Date': 1, 'to': 1, 'prevent': 1, 'To': 1, 'Released':

25、 1, 'by': 1, 'with': 1, 'Cookie': 1, 'Also': 1, 'indexOf': 1, 'there': 1, 'side': 1, 'MIT': 1, 'odd': 1, 'case': 1, 'number': 1, 'encodeURIComponent': 1, 'calling': 1, 'Hartl': 1, 'une

26、scape': 1, 'all': 1, 'removeCookie': 1, 'Read': 1, 'new': 1, 'assign': 1, 'fresh': 1, 'server': 1, '2013': 1, 'String': 1, 'empty': 1, '4': 1, 'This': 1, 'alter': 1)>>> count.most_com

27、mon(10)('s', 20), ('cookie', 18), ('options', 16), ('value', 12), ('function', 11), ('key', 10), ('var', 10), ('return', 9), ('expires', 8), ('if', 8)如何根據(jù)字典中值的大小, 對字典中的項(xiàng)排序?實(shí)際問題某班英語成績以字典形式進(jìn)行存儲(chǔ),格式為: 'ansheng': 79,

28、'Jim': 66, 'Hello': 99, .要求根據(jù)成績高低,計(jì)算學(xué)生排名。解決方案使用內(nèi)置函數(shù)sorted(),但是默認(rèn)情況下sorted()并不能對字典進(jìn)行排序,這里提供了兩種解決方法:1. 利用zip()將字典數(shù)據(jù)轉(zhuǎn)化為元組然后把值傳給sorted()進(jìn)行排序2. 傳遞sorted()函數(shù)的key參數(shù)實(shí)例先創(chuàng)建一個(gè)成績單:>>> from random import randint>>> Transcripts = x: randint(60,100) for x in 'xyzabc' >&

29、gt;> Transcripts'z': 61, 'x': 74, 'b': 81, 'c': 65, 'y': 88, 'a': 98使用sorted()進(jìn)行排序的時(shí)候是以字典的key進(jìn)行的>>> sorted(Transcripts)'a', 'b', 'c', 'x', 'y', 'z'· 第一種解決方法獲取字典的所有建>>> Transcript

30、s.keys()dict_keys('z', 'x', 'b', 'c', 'y', 'a')獲取字典所有的值>>> Transcripts.values()dict_values(61, 74, 81, 65, 88, 98)通過zip()把字典轉(zhuǎn)換為元組>>> T = zip(Transcripts.values(), Transcripts.keys()通過sorted()進(jìn)行排序得到結(jié)果>>> sorted(T)(61, 'z&#

31、39;), (65, 'c'), (74, 'x'), (81, 'b'), (88, 'y'), (98, 'a')元組在進(jìn)行比較的時(shí)候是先從第一個(gè)元素進(jìn)行比較,如果比較值為True,則后面的就不進(jìn)行比較:>>> (100, 'a') > (50, 'b')True>>> (50, 'a') > (50, 'b')# a不大于b,返回FalseFalse· 第二種解決方法>>>

32、; Transcripts.items()dict_items('z', 61), ('x', 74), ('b', 81), ('c', 65), ('y', 88), ('a', 98)# key需要傳入一個(gè)函數(shù),每次迭代Transcripts.items()的時(shí)候,把第一個(gè)元素傳入進(jìn)去,然后進(jìn)行排序>>> sorted(Transcripts.items(), key=lambda x: x1)('z', 61), ('c', 65), (&#

33、39;x', 74), ('b', 81), ('y', 88), ('a', 98)如何快速找到多個(gè)字典中的公共鍵(key)?在每一個(gè)字典中都會(huì)出現(xiàn)的鍵稱之為公共鍵。>>> from random import randint, sample# abcdefg是隨機(jī)產(chǎn)生的key,每次隨機(jī)取3-6個(gè)key>>> sample('abcdefg', randint(3, 6)'g', 'f', 'c', 'a', 'e

34、', 'd'生成隨機(jī)的字典>>> s1 = x: randint(1, 4) for x in sample('abcdefg', randint(3, 6) >>> s2 = x: randint(1, 4) for x in sample('abcdefg', randint(3, 6) >>> s3 = x: randint(1, 4) for x in sample('abcdefg', randint(3, 6) >>> s1'c&#

35、39;: 3, 'g': 1, 'e': 2>>> s2'a': 2, 'f': 2, 'g': 3, 'e': 1, 'd': 2>>> s3'a': 2, 'c': 2, 'e': 2, 'f': 4解決方案· 傳統(tǒng)的做法如下:# 生成一個(gè)列表>>> res = # 循環(huán)s1字典的所有鍵>>> for k in s1:# 如果鍵在s2和

36、s3中都存在就添加到res列表中. if k in s2 and k in s3:. res.append(k).>>> res# 得到的鍵e,在s2和s3中都存在'e'· 利用集合(set)的交集操作使用字典的keys()方法,得到一個(gè)字典的keys的集合>>> s1.keys() & s2.keys() & s3.keys()'e'· 使用map函數(shù),得到所有字典的keys的集合,然后使用reduce函數(shù),取所有字典的keys的集合的交集>>> from functoo

37、ls import reduce>>> reduce(lambda a, b: a & b, map(dict.keys, s1, s2, s3)'e'如何讓字典保持有序?解決方案使用collections.OrderedDict,以O(shè)rderedDict替代內(nèi)置字典Dict,依次將數(shù)據(jù)存入OrderedDict# 導(dǎo)入OrderedDict模塊>>> from collections import OrderedDict# 創(chuàng)建一個(gè)OrderedDict()對象>>> dic = OrderedDict()# 添加數(shù)據(jù)>>> dic'H1' = ('a', 'b')>>> dic'H2' = ('ab', 'cd')>>>

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論