在Python中,给定一个项目,如何在列表中计算它的出现次数?
一个相关但不同的问题是计算集合中每个不同元素的出现次数,将字典或列表作为直方图结果而不是单个整数。有关该问题,请参阅使用字典统计列表中的项目。
在Python中,给定一个项目,如何在列表中计算它的出现次数?
一个相关但不同的问题是计算集合中每个不同元素的出现次数,将字典或列表作为直方图结果而不是单个整数。有关该问题,请参阅使用字典统计列表中的项目。
当前回答
以下是三种解决方案:
Fastest是使用for循环并将其存储在Dict中。
import time
from collections import Counter
def countElement(a):
g = {}
for i in a:
if i in g:
g[i] +=1
else:
g[i] =1
return g
z = [1,1,1,1,2,2,2,2,3,3,4,5,5,234,23,3,12,3,123,12,31,23,13,2,4,23,42,42,34,234,23,42,34,23,423,42,34,23,423,4,234,23,42,34,23,4,23,423,4,23,4]
#Solution 1 - Faster
st = time.monotonic()
for i in range(1000000):
b = countElement(z)
et = time.monotonic()
print(b)
print('Simple for loop and storing it in dict - Duration: {}'.format(et - st))
#Solution 2 - Fast
st = time.monotonic()
for i in range(1000000):
a = Counter(z)
et = time.monotonic()
print (a)
print('Using collections.Counter - Duration: {}'.format(et - st))
#Solution 3 - Slow
st = time.monotonic()
for i in range(1000000):
g = dict([(i, z.count(i)) for i in set(z)])
et = time.monotonic()
print(g)
print('Using list comprehension - Duration: {}'.format(et - st))
后果
#解决方案1-更快
{1: 4, 2: 5, 3: 4, 4: 6, 5: 2, 234: 3, 23: 10, 12: 2, 123: 1, 31: 1, 13: 1, 42: 5, 34: 4, 423: 3}
Simple for loop and storing it in dict - Duration: 12.032000000000153
#解决方案2-快速
Counter({23: 10, 4: 6, 2: 5, 42: 5, 1: 4, 3: 4, 34: 4, 234: 3, 423: 3, 5: 2, 12: 2, 123: 1, 31: 1, 13: 1})
Using collections.Counter - Duration: 15.889999999999418
#解决方案3-缓慢
{1: 4, 2: 5, 3: 4, 4: 6, 5: 2, 34: 4, 423: 3, 234: 3, 42: 5, 12: 2, 13: 1, 23: 10, 123: 1, 31: 1}
Using list comprehension - Duration: 33.0
其他回答
使用%timeit查看哪个操作更有效。np.array计数操作应该更快。
from collections import Counter
mylist = [1,7,7,7,3,9,9,9,7,9,10,0]
types_counts=Counter(mylist)
print(types_counts)
给定列表X
import numpy as np
X = [1, -1, 1, -1, 1]
显示此列表元素的i:frequency(i)的字典为:
{i:X.count(i) for i in np.unique(X)}
输出:
{-1: 2, 1: 3}
如果您想一次计算所有值,可以使用numpy数组和bincount非常快速地完成,如下所示
import numpy as np
a = np.array([1, 2, 3, 4, 1, 4, 1])
np.bincount(a)
这给出了
>>> array([0, 3, 1, 1, 2])
要计算具有共同类型的不同元素的数量,请执行以下操作:
li = ['A0','c5','A8','A2','A5','c2','A3','A9']
print sum(1 for el in li if el[0]=='A' and el[1] in '01234')
给予
3,而不是6
建议使用numpy的bincount,但它只适用于具有非负整数的1d数组。此外,生成的数组可能会令人困惑(它包含原始列表中从最小值到最大值的整数,并将缺失的整数设置为0)。
使用numpy的更好方法是使用属性return_counts设置为True的唯一函数。它返回一个元组,其中包含一个唯一值数组和每个唯一值的出现数组。
# a = [1, 1, 0, 2, 1, 0, 3, 3]
a_uniq, counts = np.unique(a, return_counts=True) # array([0, 1, 2, 3]), array([2, 3, 1, 2]
然后我们可以将它们配对为
dict(zip(a_uniq, counts)) # {0: 2, 1: 3, 2: 1, 3: 2}
它也适用于其他数据类型和“2d列表”,例如。
>>> a = [['a', 'b', 'b', 'b'], ['a', 'c', 'c', 'a']]
>>> dict(zip(*np.unique(a, return_counts=True)))
{'a': 3, 'b': 3, 'c': 2}