Python 高效編程技巧分享
一、根據(jù)條件在序列中篩選數(shù)據(jù)
假設(shè)有一個數(shù)字列表 data, 過濾列表中的負數(shù)data = [1, 2, 3, 4, -5] # 使用列表推導式result = [i for i in data if i >= 0] # 使用 fliter 過濾函數(shù)result = filter(lambda x: x >= 0, data) 學生的數(shù)學分數(shù)以字典形式存儲,篩選其中分數(shù)大于 80 分的同學
from random import randint d = {x: randint(50, 100) for x in range(1, 21)}r = {k: v for k, v in d.items() if v > 80}
二、對字典的鍵值對進行翻轉(zhuǎn)
使用 zip() 函數(shù)zip() 函數(shù)用于將可迭代的對象作為參數(shù),將對象中對應(yīng)的元素打包成一個個元組,然后返回由這些元組組成的列表。
from random import randint, sample s1 = {x: randint(1, 4) for x in sample('abfcdrg', randint(1, 5))}d = {k: v for k, v in zip(s1.values(), s1.keys())}
三、統(tǒng)計序列中元素出現(xiàn)的頻度
某隨機序列中,找到出現(xiàn)次數(shù)最高的3個元素,它們出現(xiàn)的次數(shù)是多少方法1:
# 可以使用字典來統(tǒng)計,以列表中的數(shù)據(jù)為鍵,以出現(xiàn)的次數(shù)為值from random import randint # 構(gòu)造隨機序列data = [randint(0, 20) for _ in range(30)] # 列表中出現(xiàn)數(shù)字出現(xiàn)的次數(shù)d = dict.fromkeys(data, 0) for v in d: d[v] += 1
方法2:
# 直接使用 collections 模塊下面的 Counter 對象from collections import Counterfrom random import randint data = [randint(0, 20) for _ in range(30)] c2 = Counter(data) # 查詢元素出現(xiàn)次數(shù)c2[14] # 統(tǒng)計頻度出現(xiàn)最高的3個數(shù)c2.most_common(3) 對某英文文章單詞進行統(tǒng)計,找到出現(xiàn)次數(shù)最高的單詞以及出現(xiàn)的次數(shù)
import refrom collections import Counter # 統(tǒng)計某個文章中英文單詞的詞頻with open('test.txt', 'r', encoding='utf-8') as f: d = f.read() # 所有的單詞列表total = re.split('W+', d)result = Counter(total)print(result.most_common(10))
四、根據(jù)字典中值的大小,對字典中的項進行排序
比如班級中學生的數(shù)學成績以字典的形式存儲,請按數(shù)學成績從高到底進行排序方法1:
# 利用 zip 將字典轉(zhuǎn)化為元組,再用 sorted 進行排序from random import randint data = {x: randint(60, 100) for x in 'xyzfafs'}sorted(data)data = sorted(zip(data.values(), data.keys()))
方法2:
# 利用 sorted 函數(shù)的 key 參數(shù)from random import randint data = {x: randint(60, 100) for x in 'xyzfafs'}data.items()sorted(data.items(), key=lambda x: x[1])
五、在多個字典中找到公共鍵
實際場景:在足球聯(lián)賽中,統(tǒng)計每輪比賽都有進球的球員第一輪:{'C羅': 1, '蘇亞雷斯':2, '托雷斯': 1..}
第二輪:{'內(nèi)馬爾': 1, '梅西':2, '姆巴佩': 3..}
第三輪:{'姆巴佩': 2, 'C羅':2, '內(nèi)馬爾': 1..}
from random import randint, samplefrom functools import reduce # 模擬隨機的進球球員和進球數(shù)s1 = {x: randint(1, 4) for x in sample('abfcdrg', randint(1, 5))}s2 = {x: randint(1, 4) for x in sample('abfcdrg', randint(1, 5))}s3 = {x: randint(1, 4) for x in sample('abfcdrg', randint(1, 5))} # 首先獲取字典的 keys,然后取每輪比賽 key 的交集。由于比賽輪次數(shù)是不定的,所以使用 map 來批量操作# map(dict.keys, [s1, s2, s3]) # 然后一直累積取其交集,使用 reduce 函數(shù)reduce(lambda x, y: x & y, map(dict.keys, [s1, s2, s3]))
以上就是Python 高效編程技巧分享的詳細內(nèi)容,更多關(guān)于Python 高效編程技巧的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 使用Python webdriver圖書館搶座自動預(yù)約的正確方法2. Python sublime安裝及配置過程詳解3. Linux刪除系統(tǒng)自帶版本Python過程詳解4. Python3 json模塊之編碼解碼方法講解5. ASP基礎(chǔ)知識VBScript基本元素講解6. python 使用事件對象asyncio.Event來同步協(xié)程的操作7. Java Long類型對比分析8. Python 合并拼接字符串的方法9. ASP.NET MVC使用jQuery ui的progressbar實現(xiàn)進度條10. Python字符串到字節(jié)的轉(zhuǎn)換。雙反斜杠問題

網(wǎng)公網(wǎng)安備