liangzuojiayi 2020-05-14
通常使用迭代
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)
列表解析相对来说更快一些
字典解析:{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)
集合解析:{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)
#方法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)
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))
解决方案:使用内置函数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)
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)
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])
猜数游戏:
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))