# python - Comment puis-je compter les occurrences d'un article de liste

Mots clés : pythonlistcountpython

### meilleur 5 Réponses python - Comment puis-je compter les occurrences d'un article de liste

98

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

88

``>>> from collections import Counter >>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red'] >>> Counter(z) Counter({'blue': 3, 'red': 2, 'yellow': 1}) ``

72

``>>> l = ["a","b","b"] >>> l.count("a") 1 >>> l.count("b") 2 ``
``[[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}) ``
``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] ``

61

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

55

``>>> l = list('aaaaabbbbcccdde') >>> l ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'e'] ``
``>>> l.count('b') 4 ``
``>>> t = tuple('aabbbffffff') >>> t ('a', 'a', 'b', 'b', 'b', 'f', 'f', 'f', 'f', 'f', 'f') >>> t.count('f') 6 ``
``>>> from collections import Counter >>> c = Counter(l) >>> c['b'] 4 ``
``>>> 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}) ``