Python编程技巧(二)
2.1在列表,字典,集合中根据条件筛选数据
1.过滤列表中的负数
通常使用迭代
from random import randintdata=data=[randint(-10,10) for _ in range(10)]res=[]for x in data: if x>=0: res.append(x)print(res)
列表
filter函数:filter(lanbda x: x>=0,data)
filter(function or None,sequence)->list,tuple or string
第一个为过滤函数,第二个传入列表等
例子:
from random import randintdata=[randint(-10,10) for _ in range(10)]n_data=list(filter(lambda x:x>=0,data))print(data)print(n_data)
列表解析:[x for in data if x>=0]
例子:
#列表解析m_data=[x for x in data if x>=0]print(m_data)
列表解析相对来说更快一些
2.筛选出字典中的值
字典
字典解析:{k:v for k,v in d.items() if v>=90}
例子
#字典#生成字典d={x:randint(60,100) for x in range(1,21)}n_d={k:v for k,v in d.items() if v>90}print(d)print(n_d)
3.筛选出集合中被整除的数
集合
集合解析:{x for x in s if x%3==0}
例子
#集合data=set([randint(-10,10) for _ in range(10)])s={x for x in data if x%3==0}print(data)print(s)
2.2如何为元组的元素命名,提高可读性
#方法1#列表解包NAME,AGE,SEX,EMAIL=[x for x in range(0,4)]print(EMAIL)student=(‘T‘,‘20‘,‘male‘,‘‘)print(student[EMAIL])?#方法2from collections import namedtuplestudent=namedtuple(‘student‘,[‘name‘,‘age‘,‘sex‘,‘eamil‘])s=student(‘T‘,‘20‘,‘male‘,‘‘)print(s)print(s.name)
2.3词频统计
from random import randint#创建随机序列data=[randint(0,30) for _ in range(40)]#普通方法d=dict.fromkeys(data,0)for x in data: d[x]+=1print(data)print(d)?#方法2from collections import Counterd2=Counter(data)print(d2)#统计出现最高的print(d2.most_common(5))
统计单词
from collections import Counterimport rewith open("打开的文件") as file: data=file.read()num=Counter(re.split(‘w+‘,data))print(num.most_common(10))
2.4字典排序
解决方案:使用内置函数sorted()
1.利用zip将字典数据转化成元组
2.传递sorted函数的key参数
from random import randintdata={x:randint(60,100) for x in ‘xyzadc‘}#1n_d=sorted(zip(data.values(),data.keys()))print(data)print(n_d)#2m_d=sorted(data.items(),key=lambda x:x[1])print(m_d)
2.5如何快速找到字典中的公共键
all_data=[]for x in range(randint(3,6)): data = sample(‘abcdefg‘, randint(3, 6)) d = {x: randint(1, 4) for x in data} all_data.append(d)for x in all_data: print(x)dd=list(map(dict.keys,all_data))print(dd)ddd=reduce(lambda a,b:a&b,dd)print(ddd)
2.6字典保持有序
from time import timefrom random import randint,samplefrom collections import OrderedDictd=OrderedDict()player=list(‘ABCDEFGH‘)start=time()?for i in range(8): input() p=player.pop(randint(0,7-i)) end=time() print(i+1,p,end-start) d[p]=(i+1,end-start)?print(‘==‘*20)for k in d: print(k,d[k])
2.7实现用户的历史纪录功能
猜数游戏:
from random import randintN=randint(0,100)def guess(k): if k==N: print("right") return True if k<N: print(f‘{k} 猜小了‘) else: print(f‘{k} 猜大了‘) return Falsewhile True: line=input("请输入一个数:") if line.isdigit(): k=int(line) if guess(k): break
使用队列:
from random import randint#使用队列from collections import deque#双循环队列history=deque([],5)N=randint(0,100)def guess(k): if k==N: print("right") return True if k<N: print(f‘{k} 猜小了‘) else: print(f‘{k} 猜大了‘) return Falsewhile True: line=input("请输入一个数:") if line.isdigit(): k=int(line) history.append(k) if guess(k): break elif line==‘history‘or line==‘h?‘: print(list(history))
相关推荐
IdeaElements 2020-08-19
文山羊 2020-03-23
Kakoola 2020-02-12
wyzdeng 2019-11-19
ITxiaobaibai 2019-11-08
程序员旅途 2019-07-02
小树不倒我不倒 2010-07-28
菜鸟进化史 2012-06-29
mountainhua 2019-06-12
啊兵 2019-05-29
huojunlin 2019-05-21
yangbingqi 2018-10-29
学无涯愈进而愈惘 2018-10-02
kikaylee 2019-04-18
twentyonepilots 2018-07-17
linbossdeboke 2019-04-01
野先生 2019-03-31
retacnyue 2019-03-14
ITxiaobaibai 2019-03-12