【发布时间】:2019-03-27 01:27:39
【问题描述】:
我有一个这样的列表
L = [['16.37.123.153','119.222.456.130','38673','161','17','62','4646'],
['16.37.456.153','119.222.123.112','56388','161','17','62','4646'],..]
我想用 collections.counter 获取该列表中出现次数最多的 5 个元素。
当我使用这个解决方案时:
mostfrequentelements, counterofelements = zip(*Counter(L).most_common(5))
我得到错误:
Traceback (most recent call last):
File "hypergraph.py", line 65, in <module>
mostfrequent, countermfi = zip(*Counter(L).most_common(5))
File "/usr/lib/python2.7/collections.py", line 477, in __init__
self.update(*args, **kwds)
File "/usr/lib/python2.7/collections.py", line 567, in update
self[elem] = self_get(elem, 0) + 1
TypeError: unhashable type: 'list'
如何将它用于我的列表类型?我需要一个具有最佳时间复杂度的解决方案。
输入:
L = [['16.37.123.153','119.222.456.130','38673','161','17','62','4646'],
['16.37.456.153','119.222.123.112','56388','161','17','62','4646'],..]
输出:
Mostfrequentlelements = list of 5 most occuring sublists
Counter = list of the occurence counts of the 5 sublists
提前谢谢你, 问候:)
【问题讨论】:
-
如果要将列表用作键,则必须将它们转换为不可变类型。例如,使它们成为元组:
L = [tuple(z) for z in L]。这会给你一个元组列表,你应该没问题。 -
根据您的最新输出编辑了我的答案。
-
@Prune 很好,谢谢你:),这就像一个魅力。而且运行时似乎比我用 L.count 遍历列表要好得多。
-
如果以下答案之一解决了您的问题,您应该接受它(单击相应答案旁边的复选标记)。这有两件事。它让每个人都知道您的问题已得到解决,并为帮助您的人提供帮助。有关完整说明,请参阅here。 ;)
标签: python list nested counter element