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)) #Zeigen Sie die beiden besten
print(c.values())
import re
with open('lesson.py', 'r') as f:
words = re.findall(r'\w+', f.read().lower())
print(words) #Warum[]werden
print(collections.Counter(words).most_common(20))
Ausführungsergebnis:
{'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])
[]
[]