【问题标题】:Python - Counting the occurence of lists in a list (collections, counter)Python - 计算列表中列表的出现次数(集合,计数器)
【发布时间】:2017-03-08 17:51:02
【问题描述】:

我导入了收藏

import collections

我用它来计算列表中某些字符串的出现次数

counts = collections.Counter(list)
counts = counts.most_common()

这工作得很好。现在我的需求发生了变化,我有一个嵌套列表,我想计算该列表中列表的出现次数:

lists = [['word1', 'word2'], ['word4', 'word6'], ['word1', 'word2']]

我从单个单词列表中获得“列表”:

list = ['word1', 'word2', ...]

结果应该是这样的

[(('word1', 'word2'), 2), (('word4', 'word6'), 1)]

我希望很清楚我想要什么。

【问题讨论】:

  • 如果这是一个元组列表,就像你的例子一样,是什么阻止了你?计数器应该可以正常工作。否则,首先将嵌套列表转换为元组。
  • 无论您在问题中提到的任何内容(上述代码),都可以很好地获得您的预期结果。
  • @mgruber:检查我的解决方案
  • 查看我的编辑。括号有什么变化吗?顺便说一句:我检查了它,它适用于 [( ), ( ), ...] 但是当我编辑时,我只有括号

标签: python list collections nested counter


【解决方案1】:

collection.Counter() 工作得很好。以下是您提到的示例:

>>> from collections import Counter
>>> my_list = [('word1', 'word2'), ('word4', 'word6'), ('word1', 'word2')]

>>> Counter(my_list)
Counter({('word1', 'word2'): 2, ('word4', 'word6'): 1})  # dict object

>>> Counter(my_list).most_common()  
[(('word1', 'word2'), 2), (('word4', 'word6'), 1)] 

【讨论】:

  • Counter.items() 不能像 Couner.most_common() 那样保证顺序,并且 OP 已经知道了。
【解决方案2】:

使用hashing 使用dict()。这是一个简单的代码说明它:

lists = [('word1', 'word2'), ('word4', 'word6'), ('word1', 'word2')]

hashmap = dict()
for item in lists:
    if item in hashmap:
        hashmap[item] += 1
    else:
        hashmap[item] = 1


new_list = []

for key, value in hashmap.iteritems():
    new_list.append(((key), value))

print new_list  # output: [(('word1', 'word2'), 2), (('word4', 'word6'), 1)]

【讨论】:

    【解决方案3】:

    好的,我只是设法自己回答了这个问题。
    问题在于它是一个列表列表。
    我需要一个元组列表才能让 Counter 工作。

    我在从单词列表中收集单词时设法做到了:

    ...元组(单词[i:i+2])

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多