在Python中,给定一个项目,如何在列表中计算它的出现次数?
一个相关但不同的问题是计算集合中每个不同元素的出现次数,将字典或列表作为直方图结果而不是单个整数。有关该问题,请参阅使用字典统计列表中的项目。
在Python中,给定一个项目,如何在列表中计算它的出现次数?
一个相关但不同的问题是计算集合中每个不同元素的出现次数,将字典或列表作为直方图结果而不是单个整数。有关该问题,请参阅使用字典统计列表中的项目。
当前回答
建议使用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}
其他回答
x = ['Jess', 'Jack', 'Mary', 'Sophia', 'Karen',
'Addison', 'Joseph','Jack', 'Jack', 'Eric', 'Ilona', 'Jason']
the_item = input('Enter the item that you wish to find : ')
how_many_times = 0
for occurrence in x:
if occurrence == the_item :
how_many_times += 1
print('The occurrence of', the_item, 'in', x,'is',how_many_times)
创建了一个名字列表,其中重复了“Jack”这个名字。为了检查它的发生情况,我在名为x的列表中运行了一个for循环。每次迭代时,如果循环变量的值与从用户接收的值相同,并存储在变量the_item中,那么变量how_many_times将递增1。在获得某种价值之后。。。我们打印how_many_times,它存储单词“jack”出现的值
如果您想一次计算所有值,可以使用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])
为什么不使用Pandas?
import pandas as pd
my_list = ['a', 'b', 'c', 'd', 'a', 'd', 'a']
# converting the list to a Series and counting the values
my_count = pd.Series(my_list).value_counts()
my_count
输出:
a 3
d 2
b 1
c 1
dtype: int64
如果您正在查找特定元素的计数,例如a,请尝试:
my_count['a']
输出:
3
建议使用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}
我已经将所有建议的解决方案(以及一些新的解决方案)与perfplot(我的一个小项目)进行了比较。
清点一项
对于足够大的阵列,事实证明
numpy.sum(numpy.array(a) == 1)
比其他解决方案稍快。
清点所有项目
如前所述,
numpy.bincount(a)
是你想要的。
再现绘图的代码:
from collections import Counter
from collections import defaultdict
import numpy
import operator
import pandas
import perfplot
def counter(a):
return Counter(a)
def count(a):
return dict((i, a.count(i)) for i in set(a))
def bincount(a):
return numpy.bincount(a)
def pandas_value_counts(a):
return pandas.Series(a).value_counts()
def occur_dict(a):
d = {}
for i in a:
if i in d:
d[i] = d[i]+1
else:
d[i] = 1
return d
def count_unsorted_list_items(items):
counts = defaultdict(int)
for item in items:
counts[item] += 1
return dict(counts)
def operator_countof(a):
return dict((i, operator.countOf(a, i)) for i in set(a))
perfplot.show(
setup=lambda n: list(numpy.random.randint(0, 100, n)),
n_range=[2**k for k in range(20)],
kernels=[
counter, count, bincount, pandas_value_counts, occur_dict,
count_unsorted_list_items, operator_countof
],
equality_check=None,
logx=True,
logy=True,
)
from collections import Counter
from collections import defaultdict
import numpy
import operator
import pandas
import perfplot
def counter(a):
return Counter(a)
def count(a):
return dict((i, a.count(i)) for i in set(a))
def bincount(a):
return numpy.bincount(a)
def pandas_value_counts(a):
return pandas.Series(a).value_counts()
def occur_dict(a):
d = {}
for i in a:
if i in d:
d[i] = d[i] + 1
else:
d[i] = 1
return d
def count_unsorted_list_items(items):
counts = defaultdict(int)
for item in items:
counts[item] += 1
return dict(counts)
def operator_countof(a):
return dict((i, operator.countOf(a, i)) for i in set(a))
b = perfplot.bench(
setup=lambda n: list(numpy.random.randint(0, 100, n)),
n_range=[2 ** k for k in range(20)],
kernels=[
counter,
count,
bincount,
pandas_value_counts,
occur_dict,
count_unsorted_list_items,
operator_countof,
],
equality_check=None,
)
b.save("out.png")
b.show()