简体   繁体   English

如何在字典值上使用计数器是列表项

[英]how to use counter on dictonary values are list items

My defaultdict is as follows: 我的defaultdict如下:

defaultdict(<class 'list'>, {'DrJillStein': [18021496, 30576467, 35175054, 122130797, 227720229, 289019104, 441389311, 456794981, 774180818,763849988988211200], 'realDonaldTrump': [14669951, 22203756, 41634520, 50769180, 75541946, 245963716, 475802156, 2325495378, 720293443260456960, 729676086632656900], 'GovGaryJohnson': [15232635, 19089116, 22330739, 29255194, 44776017, 47490022, 51752944, 73206956, 90573676, 366743017], 'HillaryClinton': [15972271, 34782406, 113298560, 115740215, 325886383, 582037089, 802430450, 3044781131, 729761993461248000, 734768872625188864]})

It contains use_name and then a list of ids, in short -> key = user and value = list of ids. 它包含use_name和一个ID列表,简而言之->键=用户,值= ID列表。

I wanted first to find out common ids and then to find out the most 5 common ids in all dict, like: if id =14669951, 15513604, 22203756 我想先找出通用ID,然后再找出所有dict中最多的5个通用ID,例如:if id = 14669951、15513604、22203756

then there occurrences like: 然后出现类似这样的情况:

{[14669951:2][15513604:4][22203756:7]}

Guide me how to do that on python 3.5 or on greater version. 指导我如何在python 3.5或更高版本上执行此操作。

Initialize a Counter from collections and ask for the 5 most_common . collections初始化一个Counter ,并要求5个most_common

In order to initialize the Counter just provide it with a comprehension: 为了初始化Counter只需提供一个理解即可:

c = Counter(v for sub in d.values() for v in sub)

I added an extra id to your defaultdict to get a count of 2 for one of them. 我为您的defaultdict添加了一个额外的id ,以获取其中一个的2计数。 The result can be obtained with c.most_common(5) : 可以使用c.most_common(5)获得结果:

c.most_common(5)
[(14669951, 2),
 (720293443260456960, 1),
 (763849988988211200, 1),
 (366743017, 1),
 (245963716, 1)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM