如果您只需要单个项目的计数,请使用 count
方法:
>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3
重要提示:如果您要计算多个不同的项目,这会非常慢
每个 count
调用都会遍历整个 n
元素列表。在循环 n
次中调用 count
意味着总共 n * n
次检查,这可能对性能造成灾难性影响。
如果您想计算多个项目,请使用 Counter
,它只进行 n
个总检查。
如果您使用的是 Python 2.7 或 3.x 并且想要每个元素的出现次数,请使用 Counter
:
>>> from collections import Counter
>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> Counter(z)
Counter({'blue': 3, 'red': 2, 'yellow': 1})
isinstance
,它非常慢。因此,如果您确定要使用的数据,最好编写一个没有类型和实例检查的自定义函数。
isinstance
叫什么?即使有数百万个字符串,调用 Counter
也只涉及一次 isinstance
调用,以检查其参数是否为映射。你很可能一直误判你吃的东西。
Counter
中的优化工作已用于计算大型可迭代对象,而不是计算许多可迭代对象。与手动实现相比,使用 Counter
计算一百万个字符串的迭代会更快。如果您想用许多可迭代对象调用 update
,您可以通过将它们与 itertools.chain
加入一个可迭代对象来加快处理速度。
x = Counter({'a':5, 'b':3, 'c':7})
x.most_common()
计算列表中一项的出现次数
要计算一个列表项的出现次数,您可以使用 count()
>>> l = ["a","b","b"]
>>> l.count("a")
1
>>> l.count("b")
2
计算列表中所有项目的出现次数也称为“计数”列表或创建计数计数器。
使用 count() 计算所有项目
要计算 l
中项目的出现次数,可以简单地使用列表推导和 count()
方法
[[x,l.count(x)] for x in set(l)]
(或类似地使用字典 dict((x,l.count(x)) for x in set(l))
)
例子:
>>> l = ["a","b","b"]
>>> [[x,l.count(x)] for x in set(l)]
[['a', 1], ['b', 2]]
>>> dict((x,l.count(x)) for x in set(l))
{'a': 1, 'b': 2}
使用 Counter() 计算所有项目
或者,还有来自 collections
库的更快的 Counter
类
Counter(l)
例子:
>>> l = ["a","b","b"]
>>> from collections import Counter
>>> Counter(l)
Counter({'b': 2, 'a': 1})
计数器快多少?
我检查了统计列表的 Counter
有多快。我用几个 n
值尝试了这两种方法,似乎 Counter
快了大约 2 的常数因子。
这是我使用的脚本:
from __future__ import print_function
import timeit
t1=timeit.Timer('Counter(l)', \
'import random;import string;from collections import Counter;n=1000;l=[random.choice(string.ascii_letters) for x in range(n)]'
)
t2=timeit.Timer('[[x,l.count(x)] for x in set(l)]',
'import random;import string;n=1000;l=[random.choice(string.ascii_letters) for x in range(n)]'
)
print("Counter(): ", t1.repeat(repeat=3,number=10000))
print("count(): ", t2.repeat(repeat=3,number=10000)
和输出:
Counter(): [0.46062711701961234, 0.4022796869976446, 0.3974247490405105]
count(): [7.779430688009597, 7.962715800967999, 8.420845870045014]
Counter
对于更大的列表方式更快。列表理解方法是 O(n^2),Counter
应该是 O(n)。
isinstance
,它非常慢。因此,如果您确定要使用的数据,最好编写一个没有类型和实例检查的自定义函数。
在字典中获取每个项目出现次数的另一种方法:
dict((i, a.count(i)) for i in a)
n * (number of different items)
个操作,不包括构建集合所需的时间。使用 collections.Counter
确实要好得多。
i
实例,则不会跟随代码抛出错误,因为它会尝试在字典中输入多个具有相同值的键。 dict((i, a.count(i)) for i in a)
dict([(1, 2), (1, 3)])
返回 {1: 3}
给定一个项目,我如何计算它在 Python 列表中的出现次数?
这是一个示例列表:
>>> l = list('aaaaabbbbcccdde')
>>> l
['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'e']
列表计数
有 list.count
方法
>>> l.count('b')
4
这适用于任何列表。元组也有这种方法:
>>> t = tuple('aabbbffffff')
>>> t
('a', 'a', 'b', 'b', 'b', 'f', 'f', 'f', 'f', 'f', 'f')
>>> t.count('f')
6
集合.计数器
然后是 collections.Counter。您可以将任何可迭代对象转储到 Counter 中,而不仅仅是列表,并且 Counter 将保留元素计数的数据结构。
用法:
>>> from collections import Counter
>>> c = Counter(l)
>>> c['b']
4
计数器基于 Python 字典,它们的键是元素,因此键需要是可散列的。它们基本上就像允许冗余元素进入它们的集合。
collections.Counter 的进一步使用
您可以使用计数器中的可迭代对象添加或减去:
>>> c.update(list('bbb'))
>>> c['b']
7
>>> c.subtract(list('bbb'))
>>> c['b']
4
您还可以使用计数器进行多组操作:
>>> c2 = Counter(list('aabbxyz'))
>>> c - c2 # set difference
Counter({'a': 3, 'c': 3, 'b': 2, 'd': 2, 'e': 1})
>>> c + c2 # addition of all elements
Counter({'a': 7, 'b': 6, 'c': 3, 'd': 2, 'e': 1, 'y': 1, 'x': 1, 'z': 1})
>>> c | c2 # set union
Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1, 'y': 1, 'x': 1, 'z': 1})
>>> c & c2 # set intersection
Counter({'a': 2, 'b': 2})
为什么不是熊猫?
另一个答案表明:
为什么不使用熊猫?
Pandas 是一个通用库,但它不在标准库中。将其添加为要求并非易事。
列表对象本身以及标准库中都有针对此用例的内置解决方案。
如果您的项目还不需要 pandas,那么仅仅为此功能要求它是愚蠢的。
我已经将所有建议的解决方案(以及一些新的解决方案)与 perfplot(我的一个小项目)进行了比较。
计数一项
对于足够大的数组,事实证明
numpy.sum(numpy.array(a) == 1)
比其他解决方案略快。
https://i.stack.imgur.com/vTw7i.png
计算所有项目
numpy.bincount(a)
是你想要的。
https://i.stack.imgur.com/IE6L3.png
重现绘图的代码:
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()
numpy.random.randint(0, 100, n).tolist()
会更好。使用您的 list(numpy.random.randint(0, 100, n))
,您在 Python 列表中有 NumPy 整数,这看起来很奇怪/不切实际。
如果您想一次计算所有值,您可以使用 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
,那么 value_counts
就可以进行救援。
>>> import pandas as pd
>>> a = [1, 2, 3, 4, 1, 4, 1]
>>> pd.Series(a).value_counts()
1 3
4 2
3 1
2 1
dtype: int64
它也会根据频率自动对结果进行排序。
如果您希望结果在列表列表中,请执行以下操作
>>> pd.Series(a).value_counts().reset_index().values.tolist()
[[1, 3], [4, 2], [3, 1], [2, 1]]
为什么不使用熊猫?
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
我今天遇到了这个问题,并在我想检查 SO 之前推出了自己的解决方案。这个:
dict((i,a.count(i)) for i in a)
对于大型列表来说真的非常慢。我的解决方案
def occurDict(items):
d = {}
for i in items:
if i in d:
d[i] = d[i]+1
else:
d[i] = 1
return d
实际上比 Counter 解决方案要快一点,至少对于 Python 2.7 来说是这样。
使用 itertools.groupby() 计算所有元素
获取列表中所有元素的计数的另一种可能性是通过 itertools.groupby()
。
带有“重复”计数
from itertools import groupby
L = ['a', 'a', 'a', 't', 'q', 'a', 'd', 'a', 'd', 'c'] # Input list
counts = [(i, len(list(c))) for i,c in groupby(L)] # Create value-count pairs as list of tuples
print(counts)
退货
[('a', 3), ('t', 1), ('q', 1), ('a', 1), ('d', 1), ('a', 1), ('d', 1), ('c', 1)]
请注意它如何将前三个 a
组合为第一组,而其他 a
组则出现在列表的更下方。这是因为输入列表 L
未排序。如果这些组实际上应该是分开的,这有时可能是一个好处。
具有独特的计数
如果需要唯一组计数,只需对输入列表进行排序:
counts = [(i, len(list(c))) for i,c in groupby(sorted(L))]
print(counts)
退货
[('a', 5), ('c', 1), ('d', 2), ('q', 1), ('t', 1)]
注意:为了创建唯一计数,与 groupby
解决方案相比,许多其他答案提供了更简单、更易读的代码。但这里显示的是与重复计数示例平行。
# Python >= 2.6 (defaultdict) && < 2.7 (Counter, OrderedDict)
from collections import defaultdict
def count_unsorted_list_items(items):
"""
:param items: iterable of hashable items to count
:type items: iterable
:returns: dict of counts like Py2.7 Counter
:rtype: dict
"""
counts = defaultdict(int)
for item in items:
counts[item] += 1
return dict(counts)
# Python >= 2.2 (generators)
def count_sorted_list_items(items):
"""
:param items: sorted iterable of items to count
:type items: sorted iterable
:returns: generator of (item, count) tuples
:rtype: generator
"""
if not items:
return
elif len(items) == 1:
yield (items[0], 1)
return
prev_item = items[0]
count = 1
for item in items[1:]:
if prev_item == item:
count += 1
else:
yield (prev_item, count)
count = 1
prev_item = item
yield (item, count)
return
import unittest
class TestListCounters(unittest.TestCase):
def test_count_unsorted_list_items(self):
D = (
([], []),
([2], [(2,1)]),
([2,2], [(2,2)]),
([2,2,2,2,3,3,5,5], [(2,4), (3,2), (5,2)]),
)
for inp, exp_outp in D:
counts = count_unsorted_list_items(inp)
print inp, exp_outp, counts
self.assertEqual(counts, dict( exp_outp ))
inp, exp_outp = UNSORTED_WIN = ([2,2,4,2], [(2,3), (4,1)])
self.assertEqual(dict( exp_outp ), count_unsorted_list_items(inp) )
def test_count_sorted_list_items(self):
D = (
([], []),
([2], [(2,1)]),
([2,2], [(2,2)]),
([2,2,2,2,3,3,5,5], [(2,4), (3,2), (5,2)]),
)
for inp, exp_outp in D:
counts = list( count_sorted_list_items(inp) )
print inp, exp_outp, counts
self.assertEqual(counts, exp_outp)
inp, exp_outp = UNSORTED_FAIL = ([2,2,4,2], [(2,3), (4,1)])
self.assertEqual(exp_outp, list( count_sorted_list_items(inp) ))
# ... [(2,2), (4,1), (2,1)]
虽然这是一个很老的问题,但由于我没有找到一个班轮,所以我做了一个。
# original numbers in list
l = [1, 2, 2, 3, 3, 3, 4]
# empty dictionary to hold pair of number and its count
d = {}
# loop through all elements and store count
[ d.update( {i:d.get(i, 0)+1} ) for i in l ]
print(d)
# {1: 1, 2: 2, 3: 3, 4: 1}
以下是三种解决方案:
最快的是使用 for 循环并将其存储在字典中。
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
建议使用 numpy 的 bincount,但它仅适用于具有 非负整数的一维数组。此外,结果数组可能会令人困惑(它包含原始列表中从 min 到 max 的整数的出现,并将缺失的整数设置为 0)。
使用 numpy 执行此操作的更好方法是使用 unique 函数并将属性 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}
它也适用于其他数据类型和“二维列表”,例如
>>> a = [['a', 'b', 'b', 'b'], ['a', 'c', 'c', 'a']]
>>> dict(zip(*np.unique(a, return_counts=True)))
{'a': 3, 'b': 3, 'c': 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
sum(bool(el[0]=='A' and el[1] in '01234') for el in li)
我会使用 filter()
,以 Lukasz 为例:
>>> lst = [1, 2, 3, 4, 1, 4, 1]
>>> len(filter(lambda x: x==1, lst))
3
给定一个列表 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}
使用 %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)
可能不是最有效的,需要额外通过才能删除重复项。
功能实现:
arr = np.array(['a','a','b','b','b','c'])
print(set(map(lambda x : (x , list(arr).count(x)) , arr)))
返回:
{('c', 1), ('b', 3), ('a', 2)}
或返回 dict
:
print(dict(map(lambda x : (x , list(arr).count(x)) , arr)))
返回:
{'b': 3, 'c': 1, 'a': 2}
或者,您也可以自己实现计数器。这就是我的做法:
item_list = ['me', 'me', 'you', 'you', 'you', 'they']
occ_dict = {}
for item in item_list:
if item not in occ_dict:
occ_dict[item] = 1
else:
occ_dict[item] +=1
print(occ_dict)
输出:{'me': 2, 'you': 3, 'they': 1}
mot = ["compte", "france", "zied"]
lst = ["compte", "france", "france", "france", "france"]
dict((x, lst.count(x)) for x in set(mot))
这给了
{'compte': 1, 'france': 4, 'zied': 0}
sum([1 for elem in <yourlist> if elem==<your_value>])
这将返回 your_value 的出现次数
l2=[1,"feto",["feto",1,["feto"]],['feto',[1,2,3,['feto']]]]
count=0
def Test(l):
global count
if len(l)==0:
return count
count=l.count("feto")
for i in l:
if type(i) is list:
count+=Test(i)
return count
print(Test(l2))
这将递归计数或搜索列表中的项目,即使它在列表列表中
如果您想要特定元素的多次出现:
>>> from collections import Counter
>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> single_occurrences = Counter(z)
>>> print(single_occurrences.get("blue"))
3
>>> print(single_occurrences.values())
dict_values([3, 2, 1])
test = [409.1, 479.0, 340.0, 282.4, 406.0, 300.0, 374.0, 253.3, 195.1, 269.0, 329.3, 250.7, 250.7, 345.3, 379.3, 275.0, 215.2, 300.0]
for i in test:
print('{} numbers {}'.format(i, test.count(i)))
import pandas as pd
test = [409.1, 479.0, 340.0, 282.4, 406.0, 300.0, 374.0, 253.3, 195.1, 269.0, 329.3, 250.7, 250.7, 345.3, 379.3, 275.0, 215.2, 300.0]
#turning the list into a temporary dataframe
test = pd.DataFrame(test)
#using the very convenient value_counts() function
df_counts = test.value_counts()
df_counts
那么您可以使用 df_counts.index
和 df_counts.values
来获取数据。
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”出现的值
不定期副业成功案例分享
mylist = [1,7,7,7,3,9,9,9,7,9,10,0] print sorted(set([i for i in mylist if mylist.count(i)>2]))
list.count()
114.19 秒,numpy.unique(list, return_counts = True)
0.53 秒和 0.17 秒 { 3}。差异是惊人的。