Python的一些实用技巧(1)

xiaoxiao2021-02-28  106

一:在列表,元组和字典中根据条件筛选数据:

from random import randint data = [randint(0,100) for i in range(1,21)] ddata = {k:randint(0,100) for k in range(1,21)} #迭代器filter(function,iterable)方法 filter(lambda x:x>=50,data) filter(lambda x,y:y>=50,ddata) #列表解析方法 [x for i in data if i>=50] {k:v for k,v in ddata.items() if v>=50} 二:为元组内的每一个元素命名:提高程序的可读性 from collections import namedtuple Student = namedtuple('Student',['name','age','sex','email']) s = Student('jin',13,'male','xxxxxxxxx@qq.com') #Student(name='jin', age=13, sex='male', email='xxxxxxxxx@qq.com') 三:统计序列中元素出现的频度: from collections import Counter data = [randint(0,20) for i in range(30)] #直接生成频度的字典 c = Counter(data) #Counter({4: 3, 12: 3, 17: 3, 19: 3, 20: 3, 0: 2, 10: 2, 11: 2, 18: 2, 1: 1, 2: 1, 5: 1, 6: 1, 13: 1, 14: 1, 15: 1}) #找出频度最高的三位 c.most_common(3) #[(4, 3), (12, 3), (17, 3)] 四:字典根据值进行排序: from random import randint #将其转换成元组进行排序: data = {x:randint(0,100) for x in 'abcdefg'} tdata = zip(data.values(),data.keys()) sorted(list(tdata)) #[(20, 'd'), (53, 'c'), (55, 'g'), (73, 'a'), (83, 'e'), (83, 'f'), (100, 'b')] #根据sorted()函数的key参数进行排序: sorted(data.items(),key=lambda x:x[1]) #[('d', 20), ('c', 53), ('g', 55), ('a', 73), ('f', 83), ('e', 83), ('b', 100)] 五:通过字典的交集快速找出多个字典中的公共键: from random import randint,sample s1 = {x:randint(0,4) for x in sample('abcdefg',randint(3,6))} s2 = {x:randint(0,4) for x in sample('abcdefg',randint(3,6))} s3 = {x:randint(0,4) for x in sample('abcdefg',randint(3,6))} #通过字典的交集找出公共建 s1.keys()&s2.keys()&s3.keys() #当字典的个数较多或不确定的时候可以使用map-reduce from functools import reduce reduce(lambda x,y:x&y,map(dict.keys,[s1,s2,s3]))

转载请注明原文地址: https://www.6miu.com/read-73900.html

最新回复(0)