【问题标题】:Is there a way to count number of appearances (nested list) using Counter有没有办法使用计数器计算出现次数(嵌套列表)
【发布时间】:2015-01-20 14:37:13
【问题描述】:

我有一个嵌套列表,里面有重复项。我想获取每个列表内容及其相应的外观。所以对于嵌套列表,我有:

nested_list = [['time', 'company', 'language', 'price', 'description'],
               ['date', 'language', 'price', 'quantity'],
               ['time', 'company', 'language', 'price', 'description'],
               ['quantity', 'time', 'date', description']]

我使用了nested_list.sort(),它给出了:

['date', 'language', 'price', 'quantity']
['quantity', 'time', 'date', 'description']
['time', 'company', 'language', 'price', 'description']
['time', 'company', 'language', 'price', 'description']

因此,如果我希望将相同的项目(列表)放在一起,则一般排序可以正常工作。但是我怎样才能得到每个人的外观呢?我是否应该遍历整个列表并使用字典来记录每个嵌套列表的内容(字符串值,我确定我曾经在网上读过一些东西说列表不好用作字典键值)并计算它的外观?

无法使用普通的collections.Counter,因为TypeError: unhashable type: 'list'(如果列表用作哈希键,使用字典的另一个原因是个坏主意)。

有办法吗?我应该提取每个嵌套列表中的字符串值并使用长字符串作为键吗?

【问题讨论】:

  • 请注意,您可以散列tuple... 另请注意,“列表不适合用作字典键值” 因为你不能散列一个列表 - 字典键必须是不可变的,而列表不是,所以它不仅仅是“不好”它是不允许的。

标签: python list dictionary hash counter


【解决方案1】:

首先将每个列表转换为元组:

from collections import Counter

counts = Counter(tuple(el) for el in nested_list)
#Counter({('time', 'company', 'language', 'price', 'description'): 2, ('quantity', 'time', 'date', 'description'): 1, ('date', 'language', 'price', 'quantity'): 1})

【讨论】:

  • 最终使用了 Counter ;)
  • @PadraicCunningham 你真的应该不时加入我们python chat :)
猜你喜欢
  • 1970-01-01
  • 2012-08-03
  • 1970-01-01
  • 2016-05-28
  • 2018-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-25
相关资源
最近更新 更多