1.过滤列表中的负数
通常使用迭代
from random import randint
data=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 randint
data=[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','T5@qq.com')
print(student[EMAIL])
#方法2
from collections import namedtuple
student=namedtuple('student',['name','age','sex','eamil'])
s=student('T','20','male','T5@qq.com')
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]+=1
print(data)
print(d)
#方法2
from collections import Counter
d2=Counter(data)
print(d2)
#统计出现最高的
print(d2.most_common(5))
统计单词
from collections import Counter
import re
with 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 randint
data={x:randint(60,100) for x in 'xyzadc'}
#1
n_d=sorted(zip(data.values(),data.keys()))
print(data)
print(n_d)
#2
m_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 time
from random import randint,sample
from collections import OrderedDict
d=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 randint
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 False
while 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 False
while 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))