Dernière activité 1731079542

a sample of frequency counting words from a list, in good and bad styles

Révision 79eb76f3d2e61514d41ed0e3f1f39dea85df0fa7

dict-count.py Brut
1# You need to write a loop that counts the occurrences of each word in a list.
2#
3# Consider, if you had a big str that was a text, like say: https://zcw.guru/kristofer/hamlet
4#
5# strive to be "pythonic" in your code expressions, okay?
6
7colors = ["red", "green", "blue", "green", "red", "green"]
8
9# Not Pythonic Code
10d = {}
11for color in colors:
12 if color not in d:
13 d[color] = 0
14 d[color] += 1
15
16# Pythonic Code
17d = {}
18for color in colors:
19 d[color] = d.get(color, 0) + 1 # notice, no need for if
20
21# Another Pythonic Code
22from collections import defaultdict
23d = defaultdict(int)
24for color in colors:
25 d[color] += 1
26
27# code output
28# {'red': 2, 'green': 3, 'blue': 1}