使用字典计算列表中的项目数

问题描述 投票:0回答:10

假设我有一个项目列表,例如:

['apple', 'red', 'apple', 'red', 'red', 'pear']

我想要一个字典来计算每个项目在列表中出现的次数。因此,对于上面的列表,结果应该是:

{'apple': 2, 'red': 3, 'pear': 1}

我怎样才能用Python简单地做到这一点?


如果您只对计算列表中单个元素的实例感兴趣,请参阅如何计算列表项的出现次数?

python list count histogram
10个回答
383
投票
在 2.7 和 3.1 中,为此目的有特殊的

Counter

dict
 子类)。

>>> from collections import Counter >>> Counter(['apple','red','apple','red','red','pear']) Counter({'red': 3, 'apple': 2, 'pear': 1})
    

330
投票
我喜欢:

counts = dict() for i in items: counts[i] = counts.get(i, 0) + 1

.get 允许您在键不存在时指定默认值。


75
投票
只需使用列表属性count\

i = ['apple','red','apple','red','red','pear'] d = {x:i.count(x) for x in i} print d

输出:

{'pear': 1, 'apple': 2, 'red': 3}
    

63
投票
>>> L = ['apple','red','apple','red','red','pear'] >>> from collections import defaultdict >>> d = defaultdict(int) >>> for i in L: ... d[i] += 1 >>> d defaultdict(<type 'int'>, {'pear': 1, 'apple': 2, 'red': 3})
    

32
投票
我一直认为对于这么琐碎的任务,我不想导入任何东西。但我可能是错的,具体取决于集合。计数器是否更快。

items = "Whats the simpliest way to add the list items to a dictionary " stats = {} for i in items: if i in stats: stats[i] += 1 else: stats[i] = 1 # bonus for i in sorted(stats, key=stats.get): print("%d×'%s'" % (stats[i], i))

我认为这可能比使用 count() 更好,因为它只会遍历可迭代一次,而 count 可能会在每次迭代时搜索整个事物。我使用这种方法来解析许多兆字节的统计数据,并且它总是相当快。


4
投票
L = ['apple','red','apple','red','red','pear'] d = {} [d.__setitem__(item,1+d.get(item,0)) for item in L] print d

给予

{'pear': 1, 'apple': 2, 'red': 3}


    


1
投票
如果您使用 Numpy,

unique

 函数可以通过传递 
return_counts=True
:
告诉您每个值出现了多少次

>>> data = ['apple', 'red', 'apple', 'red', 'red', 'pear'] >>> np.unique(data, return_counts=True) (array(['apple', 'pear', 'red'], dtype='<U5'), array([2, 1, 3]))
计数与找到的不同元素的顺序相同;因此,我们可以使用

通常的技巧来创建所需的字典(将两个元素作为单独的参数传递给zip

):

>>> dict(zip(*np.unique(data, return_counts=True))) {'apple': 2, 'pear': 1, 'red': 3}


如果您

特别有一个由小整数组成的大输入Numpy数组,您可能会从bincount

中获得更好的性能:

>>> data = np.random.randint(10, size=100) >>> data array([1, 0, 0, 3, 3, 4, 2, 4, 4, 0, 4, 8, 7, 4, 4, 8, 7, 0, 0, 2, 4, 2, 0, 9, 0, 2, 7, 0, 7, 7, 5, 6, 6, 8, 4, 2, 7, 6, 0, 3, 6, 3, 0, 4, 8, 8, 9, 5, 2, 2, 5, 1, 1, 1, 9, 9, 5, 0, 1, 1, 9, 5, 4, 9, 5, 2, 7, 3, 9, 0, 1, 4, 9, 1, 1, 5, 4, 7, 5, 0, 3, 5, 1, 9, 4, 8, 8, 9, 7, 7, 7, 5, 6, 3, 2, 4, 3, 9, 6, 0]) >>> np.bincount(data) array([14, 10, 9, 8, 14, 10, 6, 11, 7, 11])
输出数组中的第 

n

 值表示 
n
 出现的次数,因此如果需要,我们可以使用 
enumerate
 创建字典:

>>> dict(enumerate(np.bincount(data))) {0: 14, 1: 10, 2: 9, 3: 8, 4: 14, 5: 10, 6: 6, 7: 11, 8: 7, 9: 11}
    

0
投票
这是一个简单的答案m8!

def equalizeArray(arr): # Counting the frequency of each element in the array freq = {} for i in arr: if i not in freq: freq[i] = 1 else: freq[i] += 1 # Finding the element with the highest frequency max_freq = max(freq.values()) # Calculating the number of deletions required for key,value in freq.items(): if value == max_freq: print(key,"been repeated:",value,"times")
    

0
投票
首先创建一个要计数的元素列表

>>> elements = [1, 2, 3, 2, 1, 3, 2, 1, 1, 4, 5, 4, 4]


创建一个空字典,我们也对列表做同样的事情

>>> counts = {}
创建一个 for 循环来计算“key”的出现次数,对于每次出现我们加 1

>>> for element in elements: >>> if element in counts: >>> counts[element] +=1
我们检查之前是否遇到过该键,如果没有,我们添加 1,如果没有,我们使用“else”,这样它就保持不变

>>> else: >>> counts[element] = 1
现在我们将使用 'items() 打印计数,以便我们可以创建键值对的序列

>>> for element, count in counts.items(): >>> print(element, ":", count)
这里的 items() 方法向我们展示了键值对,所以我们问,“对于元素中的元素,将之前的数据加载到‘count’中,并将其更新为键值对序列,这就是该项目的内容() 是

没有注释的代码:

elements = [1, 2, 3, 2, 1, 3, 2, 1, 1, 4, 5, 4, 4] counts = {} for element in elements: if element in counts: counts[element] += 1 else: counts[element] = 1 for element, count in counts.items(): print(element, ":", count)
输出:

1:4 2:3 3:2 4:3 5:1
    

-1
投票
mylist = [1,2,1,5,1,1,6,'a','a','b'] result = {} for i in mylist: result[i] = mylist.count(i) print(result)
    
© www.soinside.com 2019 - 2024. All rights reserved.