Python 高效編程技巧分享
一、根據條件在序列中篩選數據
假設有一個數字列表 data, 過濾列表中的負數data = [1, 2, 3, 4, -5] # 使用列表推導式result = [i for i in data if i >= 0] # 使用 fliter 過濾函數result = filter(lambda x: x >= 0, data) 學生的數學分數以字典形式存儲,篩選其中分數大于 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}
二、對字典的鍵值對進行翻轉
使用 zip() 函數zip() 函數用于將可迭代的對象作為參數,將對象中對應的元素打包成一個個元組,然后返回由這些元組組成的列表。
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())}
三、統計序列中元素出現的頻度
某隨機序列中,找到出現次數最高的3個元素,它們出現的次數是多少方法1:
# 可以使用字典來統計,以列表中的數據為鍵,以出現的次數為值from random import randint # 構造隨機序列data = [randint(0, 20) for _ in range(30)] # 列表中出現數字出現的次數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) # 查詢元素出現次數c2[14] # 統計頻度出現最高的3個數c2.most_common(3) 對某英文文章單詞進行統計,找到出現次數最高的單詞以及出現的次數
import refrom collections import Counter # 統計某個文章中英文單詞的詞頻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))
四、根據字典中值的大小,對字典中的項進行排序
比如班級中學生的數學成績以字典的形式存儲,請按數學成績從高到底進行排序方法1:
# 利用 zip 將字典轉化為元組,再用 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 函數的 key 參數from random import randint data = {x: randint(60, 100) for x in 'xyzfafs'}data.items()sorted(data.items(), key=lambda x: x[1])
五、在多個字典中找到公共鍵
實際場景:在足球聯賽中,統計每輪比賽都有進球的球員第一輪:{'C羅': 1, '蘇亞雷斯':2, '托雷斯': 1..}
第二輪:{'內馬爾': 1, '梅西':2, '姆巴佩': 3..}
第三輪:{'姆巴佩': 2, 'C羅':2, '內馬爾': 1..}
from random import randint, samplefrom functools import reduce # 模擬隨機的進球球員和進球數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 的交集。由于比賽輪次數是不定的,所以使用 map 來批量操作# map(dict.keys, [s1, s2, s3]) # 然后一直累積取其交集,使用 reduce 函數reduce(lambda x, y: x & y, map(dict.keys, [s1, s2, s3]))
以上就是Python 高效編程技巧分享的詳細內容,更多關于Python 高效編程技巧的資料請關注好吧啦網其它相關文章!
相關文章: