5、如何快速找到多个字典中的公共键(key) 6 如何让字典保持有序 7 如何实现用户的历史记录功能(最多n条)...
生活随笔
收集整理的這篇文章主要介紹了
5、如何快速找到多个字典中的公共键(key) 6 如何让字典保持有序 7 如何实现用户的历史记录功能(最多n条)...
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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 reduceprint(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:breakresult:
請輸入數字5
輸入的是數字
請輸入數字6
輸入的是數字
請輸入數字7
輸入的是數字
請輸入數字8
輸入的是數字
請輸入數字history
deque(['5', '6', '7', '8'], maxlen=4)
請輸入數字100
輸入的是數字
請輸入數字history
deque(['6', '7', '8', '100'], maxlen=4)
請輸入數字
?
轉載于:https://www.cnblogs.com/laonicc/p/6720892.html
總結
以上是生活随笔為你收集整理的5、如何快速找到多个字典中的公共键(key) 6 如何让字典保持有序 7 如何实现用户的历史记录功能(最多n条)...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 有名信号量sem_open和内存信号量s
- 下一篇: pthread_create()创建线程