工做中常常要處理各類各樣的數據,遇到項目趕進度的時候本身寫函數容易浪費時間。
Python 中有不少內置函數幫你提升工做效率!python
1.假設有一個數字列表 data, 過濾列表中的負數
列表推導式編程
result = [i for i in data if i >= 0]
filtersegmentfault
result = filter(lambda x: x>= 0, data)
2.學生的數學分數以字典形式存儲,篩選其中分數大於 80 分的同窗微信
d = {x:randint(50, 100) for x in range(1, 21)}
{k: v for k, v in d.items() if v > 80}
使用 zip() 函數dom
zip() 函數用於將可迭代的對象做爲參數,將對象中對應的元素打包成一個個元組,而後返回由這些元組組成的列表。
>>> s1 = {x: randint(1, 4) for x in sample('abfcdrg', randint(1,5))} >>> s1 {'b': 1, 'f': 4, 'g': 3, 'r': 1} >>> d = {k:v for k, v in zip(s1.values(), s1.keys())} >>> d {1: 'r', 4: 'f', 3: 'g'}
隨機序列以下:函數
data = [randint(0,20) for _ in range(20)]
方法1: 能夠使用字典來統計,以列表中的數據爲鍵,以出現的次數爲值spa
from random import randint def demo(): data = [randint(0, 20) for _ in range(30)] # 列表中出現數字出現的次數 d = dict.fromkeys(data, 0) for v in li: d[v] += 1 return d
方法2:直接使用 collections 模塊下面的 Counter 對象code
>>> data = [randint(0, 20) for _ in range(30)] >>> data [7, 8, 5, 16, 10, 16, 8, 17, 11, 18, 11, 17, 15, 7, 2, 19, 5, 16, 17, 17, 12, 19, 9, 10, 0, 20, 11, 2, 11, 10] >>> c2 = Counter(data) >>> c2 Counter({17: 4, 11: 4, 16: 3, 10: 3, 7: 2, 8: 2, 5: 2, 2: 2, 19: 2, 18: 1, 15: 1, 12: 1, 9: 1, 0: 1, 20: 1}) >>> c2[14] 4 >>> c2.most_common(3) # 統計頻度出現最高的3個數 [(17, 4), (11, 4), (16, 3)]
經過上面的練習,咱們知道能夠用 Counter 來解決對象
import re from 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))
好比班級中學生的數學成績以字典的形式存儲:排序
{"Lnad": 88, "Jim", 71...}
請按數學成績從高到底進行排序!
方法1: 利用 zip 將字典轉化爲元祖,再用 sorted 進行排序
>>> data = {x: randint(60, 100) for x in "xyzfafs"} >>> data {'x': 73, 'y': 69, 'z': 76, 'f': 61, 'a': 64, 's': 100} >>> sorted(data) ['a', 'f', 's', 'x', 'y', 'z'] >>> data = sorted(zip(data.values(), data.keys())) >>> data [(61, 'f'), (64, 'a'), (69, 'y'), (73, 'x'), (76, 'z'), (100, 's')]
方法2: 利用 sorted 函數的 key 參數
>>> data.items() >>> dict_items([('x', 64), ('y', 74), ('z', 66), ('f', 62), ('a', 80), ('s', 72)]) >>> sorted(data.items(), key=lambda x: x[1]) [('f', 62), ('x', 64), ('z', 66), ('s', 72), ('y', 74), ('a', 80)]
實際場景:在足球聯賽中,統計每輪比賽都有進球的球員
第一輪: {"C羅": 1, "蘇亞雷斯":2, "託雷斯": 1..}
第二輪: {"內馬爾": 1, "梅西":2, "姆巴佩": 3..}
第三輪: {"姆巴佩": 2, "C羅":2, "內馬爾": 1..}
模擬隨機的進球球員和進球數
>>> s1 = {x: randint(1, 4) for x in sample('abfcdrg', randint(1,5))} >>> s1 {'d': 3, 'g': 2} >>> s2 = {x: randint(1, 4) for x in sample('abfcdrg', randint(1,5))} >>> s2 {'b': 4, 'g': 1, 'f': 1, 'r': 4, 'd': 3} >>> s3 = {x: randint(1, 4) for x in sample('abfcdrg', randint(1,5))} >>> s3 {'b': 4, 'r': 4, 'a': 2, 'g': 3, 'c': 4}
首先獲取字典的 keys,而後取每輪比賽 key 的交集
因爲比賽輪次數是不定的,因此使用 map 來批量操做
map(dict.keys, [s1, s2, s3])
而後一直累積取其交集, 使用 reduce 函數
reduce(lambda x,y: x & y, map(dict.keys, [s1, s2, s3]))
一行代碼搞定!
瞭解更多內容,煩請關注本人公衆號, Python編程與實戰