Python 如何计算列表项的出现次数?

Python 如何计算列表项的出现次数?,python,list,count,Python,List,Count,给定一个项目,如何在Python中计算其在列表中的出现次数?如果只需要一个项目的计数,请使用count方法: >>> [1, 2, 3, 4, 1, 4, 1].count(1) 3 有关计数性能的重要注意事项 如果要计算多个项目,请不要使用此选项 在循环中调用count需要为每个count调用单独传递列表,这可能会对性能造成灾难性影响 如果要计算所有项目,甚至只是多个项目,请使用计数器,如其他答案中所述。列表。计数(x)返回列表中出现的次数x 见: 如果您使用的是Pytho

给定一个项目,如何在Python中计算其在列表中的出现次数?

如果只需要一个项目的计数,请使用
count
方法:

>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3
有关计数性能的重要注意事项 如果要计算多个项目,请不要使用此选项

在循环中调用
count
需要为每个
count
调用单独传递列表,这可能会对性能造成灾难性影响

如果要计算所有项目,甚至只是多个项目,请使用计数器,如其他答案中所述。

列表。计数(x)
返回列表中出现的次数
x

见:

如果您使用的是Python 2.7或3.x,并且需要每个元素的出现次数,请使用:

来自集合导入计数器的
>>
>>>z=[“蓝色”、“红色”、“蓝色”、“黄色”、“蓝色”、“红色”]
>>>计数器(z)
计数器({'blue':3,'red':2,'yellow':1})
#Python>=2.6(默认dict)和&<2.7(计数器,订单数据)
从集合导入defaultdict
def计数\未分类\列表\项目(项目):
"""
:param items:要计数的哈希项的iterable
:类型项:iterable
:返回:像Py2.7计数器这样的计数记录
:rtype:dict
"""
计数=defaultdict(int)
对于项目中的项目:
计数[项目]+=1
返回指令(计数)
#Python>=2.2(生成器)
def计数\排序\列表\项目(项目):
"""
:param items:要计数的已排序iterable项
:类型项:已排序的iterable
:返回(项、计数)元组的生成器
:rtype:生成器
"""
如果不是项目:
返回
elif len(项目)=1:
收益率(项目[0],1)
返回
上一个项目=项目[0]
计数=1
对于项目[1:]中的项目:
如果上一个项目==项目:
计数+=1
其他:
收益率(上一个项目,计数)
计数=1
上一项=上一项
产量(项目、数量)
返回
导入单元测试
类TestListCounters(unittest.TestCase):
def测试\计数\未分类\列表\项目(自身):
D=(
([], []),
([2], [(2,1)]),
([2,2], [(2,2)]),
([2,2,2,2,3,3,5,5], [(2,4), (3,2), (5,2)]),
)
对于D中的输入、输出:
计数=计数\未分类\列表\项目(inp)
打印输入、输出、计数
自我评估质量(计数、记录(经验输出))
inp,exp_outp=UNSORTED_WIN=([2,2,4,2],(2,3)、(4,1)])
自身资产质量(dict(exp\U OUTPT)、计数\U未分类\U列表\U项目(inp))
def测试\计数\排序\列表\项目(自身):
D=(
([], []),
([2], [(2,1)]),
([2,2], [(2,2)]),
([2,2,2,2,3,3,5,5], [(2,4), (3,2), (5,2)]),
)
对于D中的输入、输出:
计数=列表(计数\排序\列表\项目(inp))
打印输入、输出、计数
self.assertEqual(计数、输出)
inp,exp_outp=UNSORTED_FAIL=([2,2,4,2],(2,3)、(4,1)])
self.assertEqual(exp\u outp,list(count\u sorted\u list\u items(inp)))
# ... [(2,2), (4,1), (2,1)]

要计算具有相同类型的不同元素的数量:

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

获取字典中每个项目出现次数的另一种方法:

dict((i, a.count(i)) for i in a)

我今天遇到了这个问题,并在我想检查之前推出了自己的解决方案。这:

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

实际上要比计数器解决方案快一点,至少对于Python 2.7来说是这样。

如果您想同时对所有值进行计数
可以使用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])

统计列表中一个项目的出现次数

对于仅计算一个列表项的出现次数,可以使用
count()

统计列表中所有项目的出现次数也称为“清点”列表或创建清点计数器

使用count()计数所有项目。

要计算
l
中项目的出现次数,只需使用列表理解和
count()
方法即可

[[x,l.count(x)] for x in set(l)]
>>> l.count('b')
4
(或类似地使用字典
dict((x,l.count(x)),表示集合(l)中的x)

例如:

>>> 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(l)
例如:

>>> l = ["a","b","b"]
>>> from collections import Counter
>>> Counter(l)
Counter({'b': 2, 'a': 1})
计数器快多少?

我检查了计数器清点清单的速度。我用几个
n
的值尝试了这两种方法,似乎
计数器的速度快了大约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]
给定一个项目,如何计算它在Python列表中的出现次数? 下面是一个示例列表:

>>> l = list('aaaaabbbbcccdde')
>>> l
['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'e']
list.count
这里有
list.count
方法

[[x,l.count(x)] for x in set(l)]
>>> 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
然后是收款台。您可以将任何iterable转储到计数器中,而不仅仅是列表,计数器将保留元素计数的数据结构

用法:

>>> from collections import Counter
>>> c = Counter(l)
>>> c['b']
4
计数器基于Python字典,它们的键是元素,因此键需要是可散列的。它们基本上类似于允许冗余元素进入其中的集合

进一步使用
collections.Counter
您可以使用iterables从计数器中进行加法或减法运算:

>>> 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是一个公共库,但它不在标准库中。将其添加为需求是非常重要的

在列表对象本身和标准库中都有用于此用例的内置解决方案<
import pandas as pd

l = ['a', 'b', 'c', 'd', 'a', 'd', 'a']

# converting the list to a Series and counting the values
my_count = pd.Series(l).value_counts()
my_count
a    3
d    2
b    1
c    1
dtype: int64
my_count['a']
3
sum([1 for elem in <yourlist> if elem==<your_value>])
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))


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,
    )
>>> 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]]
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)}
print(dict(map(lambda x  : (x , list(arr).count(x)) , arr)))
{'b': 3, 'c': 1, 'a': 2}
>>> 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])
def countfrequncyinarray(arr1):
    r=len(arr1)
    return {i:arr1.count(i) for i in range(1,r+1)}
arr1=[4,4,4,4]
a=countfrequncyinarray(arr1)
print(a)
# 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}
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)]
counts = [(i, len(list(c))) for i,c in groupby(sorted(L))]
print(counts)
[('a', 5), ('c', 1), ('d', 2), ('q', 1), ('t', 1)]
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))
#Solution 1 - Faster
{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
#Solution 2 - Fast
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
#Solution 3 - Slow
{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
# 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}
>>> lst = [1, 2, 3, 4, 1, 4, 1]
>>> len(filter(lambda x: x==1, lst))
3
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))
 import numpy as np
 X = [1, -1, 1, -1, 1]
{i:X.count(i) for i in np.unique(X)}
{-1: 2, 1: 3}
 from collections import Counter
 mylist = [1,7,7,7,3,9,9,9,7,9,10,0] 
 types_counts=Counter(mylist)
 print(types_counts)
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)))