[PYTHON] collections.

lesson.py


import collections

d = {}
l = ['a', 'a', 'a', 'b', 'b', 'c']
for word in l:
    if word not in d:
        d[word] = 0
    d[word] += 1
print(d)

d = {}
for word in l:
    d.setdefault(word, 0)
    d[word] += 1
print(d)

d = collections.defaultdict(int)
for word in l:
    d[word] += 1
print(d)

c = collections.Counter()
for word in l:
    c[word] += 1
print(c)
print(c.most_common(2)) #Montrez les deux premiers
print(c.values())

import re
with open('lesson.py', 'r') as f:
    words = re.findall(r'\w+￿', f.read().lower())
    print(words) #Pourquoi[]devenir
    print(collections.Counter(words).most_common(20))

Résultat de l'exécution:

{'a': 3, 'b': 2, 'c': 1}
{'a': 3, 'b': 2, 'c': 1}
defaultdict(<class 'int'>, {'a': 3, 'b': 2, 'c': 1})
Counter({'a': 3, 'b': 2, 'c': 1})
[('a', 3), ('b', 2)]
dict_values([3, 2, 1])
[]
[]

Recommended Posts

collections.
Utilisez des collections.