# python python统计列表中的重复项出现的次数 - 如何统计列表项的出现次数？

## list重复项 numpy统计出现次数 (15)

``````from collections import Counter
country=['Uruguay', 'Mexico', 'Uruguay', 'France', 'Mexico']
count_country = Counter(country)
output_list= []

for i in count_country:
output_list.append([i,count_country[i]])
print output_list
``````

``````[['Mexico', 2], ['France', 1], ['Uruguay', 2]]
``````

`list.count(x)`返回`x`出现在列表中的次数

``````>>> 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}
``````

``````>>> l = ["a","b","b"]
>>> l.count("a")
1
>>> l.count("b")
2
``````

``````[[x,l.count(x)] for x in set(l)]
``````

（或者`dict((x,l.count(x)) for x in set(l))`的字典`dict((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(l)
``````

``````>>> l = ["a","b","b"]
>>> from collections import Counter
>>> Counter(l)
Counter({'b': 2, 'a': 1})
``````

Counter有多快？

``````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]
``````

``````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

``````import numpy as np
a = np.array([1, 2, 3, 4, 1, 4, 1])
np.bincount(a)
``````

``````>>> array([0, 3, 1, 1, 2])
``````

``````>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3
``````

# 给定一个项目，我如何计算它在Python中的列表中的出现次数？

``````>>> l = list('aaaaabbbbcccdde')
>>> l
['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'e']
``````

## `list.count`

`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`

``````>>> from collections import Counter
>>> c = Counter(l)
>>> c['b']
4
``````

### 进一步使用`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})
``````

## 为什么不是熊猫？

### 计数一个项目

``````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,
)
``````

2。

``````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

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
``````

``````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.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)]
``````

``````from functools import reduce #python 3

>>> l = [[1,2,3],[4,5,6], [7], [8,9]]
>>> reduce(lambda x,y: x+y,l)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
``````

`reduce`版本的更快方法是

``````>>> import operator
>>> l = [[1,2,3],[4,5,6], [7], [8,9]]
>>> reduce(operator.concat, l)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
``````