[英]Count occurrence of a list in a List of Lists in Python
I have a list that looks something like this: 我有一个看起来像这样的列表:
co_list = [[387, 875, 125, 822], [397, 994, 135, 941], [397, 994, 135, 941], [397, 994, 135, 941], [397, 994, 135, 941], [1766, 696, 1504, 643]. . . ]
I need to count the number of identical co-ordinates lists and return the count, 4 in this case. 我需要计算相同坐标列表的数量并返回计数,在这种情况下为4。
So far I have tried: 到目前为止,我已经尝试过:
def most_common(lst):
lst = list(lst)
return max(set(lst), key=lst.count)
for each in kk :
print most_common(each)
Using which I get the most occurring element in each list. 使用它,我可以在每个列表中获得最多的元素。 But my intention is to get a list if it's occurrence is more than 3.
但我的意图是获取列表(如果出现的次数大于3)。
Expected Output: 预期产量:
(element, count) = ([397, 994, 135, 941], 4)
Any help would be appreciated. 任何帮助,将不胜感激。 Thanks.
谢谢。
You can use collections.Counter
for that task: 您可以将
collections.Counter
用于该任务:
from collections import Counter
co_list = [[387, 875, 125, 822], [397, 994, 135, 941], [397, 994, 135, 941], [397, 994, 135, 941], [397, 994, 135, 941], [1766, 696, 1504, 643]]
common_list, appearances = Counter([tuple(x) for x in co_list]).most_common(1)[0] # Note 1
if appearances > 3:
print((list(common_list), appearances)) # ([397, 994, 135, 941], 4)
else:
print('No list appears more than 3 times!')
1) The inner list
s are converted to tuple
s because Counter
builds a dict
and list
s being not hashable cannot be used as key
s. 1)内部
list
s被转换为tuple
s,因为Counter
生成了一个dict
并且不可哈希的list
s不能用作key
s。
from collections import Counter
def get_most_common_x_list(origin_list, x):
counter = Counter(tuple(item) for item in origin_list)
for item, count in most_common_list = counter.most_common():
if count > x:
yield list(item), count
else:
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.