[英]How to count unique key elements in a tuple in a defaultdict (python)?
[英]How to Count Unique record for defaultdict in python3
我在Python3中較新,現在陷入了一個問題。
問題陳述:我有一個defaultdict,其中一個鍵有多個值。 在這些多個值中,存在相似和不同的值。
現在,我想為每個鍵獲取一個摘要(基於唯一記錄的計數數)。
字典(命名為“ d”),如下所示defaultdict(,{'0':['“ 126”},','“ 115”},','“ 60”},'],'1':[' “ 126”},'],'2':['“ 126”},','“ 126”},','“ 126”},','“ 148”},','“ 99”} ,'],'3':['“ 126”},','“” 226“},'],'4':['” 126“},','” 90“},'],})
預期產量:
0: countALL :3; 1: countALL :1; 2: countALL :3; 3: countALL :2; 4: countALL :2;
例如,對於鍵“ 2”,有3條記錄,分別為126、148中的1和99中的1。因此,由於存在三種類型的唯一記錄,因此摘要將為3。
這是針對我的研究的Python3程序,我正在使用它來區分來自網絡的不同類型的流量。
預期結果:
0: countALL :3; 1: countALL :1; 2: countALL :3; 3: countALL :2; 4: countALL :2;
這是我對您的問題的解釋的答案,盡管我的解釋可能不正確。
from collections import Counter
data = {1: [2,3,4,3,4], 2: [6,5,3,5]}
for key, values in data.items():
print(f'{key} has the following unique counts {Counter(values)}')
輸出以下內容:
1 has the following unique counts Counter({3: 2, 4: 2, 2: 1})
2 has the following unique counts Counter({5: 2, 6: 1, 3: 1})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.