5、如何快速找到多个字典中的公共键(key)
from random import randint,sample #随机取数 # a = sample("ABCDEF",randint(5,6)) # print(a) # b1 = {x:randint(1,4) for x in sample("ABCDEF",randint(3,6))} # b2 = {x:randint(1,4) for x in sample("ABCDEF",randint(3,6))} # b3 = {x:randint(1,4) for x in sample("ABCDEF",randint(3,6))} # print(b1,b2,b3) b1 = {'A': 4, 'D': 4, 'F': 4, 'B': 3} b2 = {'A': 4, 'B': 3, 'C': 4, 'D': 3, 'F': 4, 'E': 4} b3 = {'A': 1, 'B': 1, 'C': 1, 'D': 4, 'F': 4} #找出公共key方法一: ret = [] for x in b1: if x in b2 and x in b3: ret.append(x) print(ret) #方法二通过集合方式找出交集 s1 = set(b1.keys()) s2 = set(b2.keys()) s3 = set(b3.keys()) info = s1 & s2 & s3 print(info) map(dict.keys,[s1,s2,s3]) from functools import reduce print(reduce(lambda a,b:a & b,map(dict.keys,[b1,b2,b3])))
6 如何让字典保持有序
我们创建的字典默认是无序的,python有个模块QrderedDict可以记录存入元素的顺序,然后迭代时会按顺序取出
from collections import OrderedDict dict1 = OrderedDict() dict1["1"] = 1 dict1["2"] = 2 dict1["3"] = 3 dict1["4"] = 4 print(dict1) for k,v in dict1.items(): print(k,v)
result:
OrderedDict([('1', 1), ('2', 2), ('3', 3), ('4', 4)])
1 1
2 2
3 3
4 4
7 如何实现用户的历史记录功能(最多n条)
python标准库里有个存储队列的模块deque,可以用来存储历史数据
from collections import deque s = deque([],4) while True: d = input("请输入数字") if d.isdigit(): print("输入的是数字") s.append(d) elif d == "history": print(s) else: break
result:
请输入数字5
输入的是数字
请输入数字6
输入的是数字
请输入数字7
输入的是数字
请输入数字8
输入的是数字
请输入数字history
deque(['5', '6', '7', '8'], maxlen=4)
请输入数字100
输入的是数字
请输入数字history
deque(['6', '7', '8', '100'], maxlen=4)
请输入数字