【问题标题】:Getting the 5 most occuring elements in a nested list (of strings) with collections.Counter使用 collections.Counter 获取嵌套列表(字符串)中出现次数最多的 5 个元素
【发布时间】: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


【解决方案1】:

您传递的是嵌套列表而不是序列。在使用计数器之前,您需要访问列表中的每个列表L

您可以创建一个计数器列表并稍后获取值。

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']]

from collections import Counter

c = [Counter(i) for i in L]

for item in c:
    print(item.most_common(5))

更新

要计算每个列表,您可以将它们加入字符串并计算它们:

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']]

from collections import Counter

L = [','.join(i) for i in L]
c = Counter(L).most_common(5)

Mostfrequentlelements = [i[0] for i in c]
Counts = [i[1] for i in c]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    • 2015-04-24
    • 2019-03-24
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    相关资源
    最近更新 更多