[英]Python - Counting the occurence of lists in a list (collections, counter)
I imported collections 我导入了收藏
import collections
I use it to count the occurence of certain strings in a list 我用它来计算列表中某些字符串的出现
counts = collections.Counter(list)
counts = counts.most_common()
This works perfectly fine. 这工作得很好。 Now my needs changed and I have a nested list and I want to count the occurence of lists in that list: 现在,我的需求发生了变化,并且我有一个嵌套列表,我想计算该列表中列表的出现次数:
lists = [['word1', 'word2'], ['word4', 'word6'], ['word1', 'word2']]
I get "lists" from a list of single words: 我从单词列表中获得“列表”:
list = ['word1', 'word2', ...]
The result should look like this 结果应如下所示
[(('word1', 'word2'), 2), (('word4', 'word6'), 1)]
I hope it is clear what I want. 我希望很清楚我想要什么。
collection.Counter()
works perfectly fine. collection.Counter()
工作得很好。 Below is the example you mentioned: 下面是您提到的示例:
>>> 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)]
Use hashing
using dict()
. 使用dict()
使用hashing
。 This is a simple code illustrating it: 这是一个说明它的简单代码:
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)]
Okay I just manage to answer the question on my own. 好吧,我只能自己回答这个问题。
The problem was that it was a list of lists. 问题在于这是一个列表列表。
I needed to have a list of tupples to get Counter working. 我需要一张纸巾清单才能使Counter工作。
I managed to do that while collecting the words from the list of words: 我设法从单词列表中收集了单词:
... tuple(words[i:i+2]) ...元组(words [i:i + 2])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.