kristofer gist felülvizsgálása . Revízióhoz ugrás
Nincsenek változtatások
kristofer gist felülvizsgálása . Revízióhoz ugrás
1 file changed, 28 insertions
dict-count.py(fájl létrehozva)
@@ -0,0 +1,28 @@ | |||
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 | + | ||
7 | + | colors = ["red", "green", "blue", "green", "red", "green"] | |
8 | + | ||
9 | + | # Not Pythonic Code | |
10 | + | d = {} | |
11 | + | for color in colors: | |
12 | + | if color not in d: | |
13 | + | d[color] = 0 | |
14 | + | d[color] += 1 | |
15 | + | ||
16 | + | # Pythonic Code | |
17 | + | d = {} | |
18 | + | for color in colors: | |
19 | + | d[color] = d.get(color, 0) + 1 # notice, no need for if | |
20 | + | ||
21 | + | # Another Pythonic Code | |
22 | + | from collections import defaultdict | |
23 | + | d = defaultdict(int) | |
24 | + | for color in colors: | |
25 | + | d[color] += 1 | |
26 | + | ||
27 | + | # code output | |
28 | + | # {'red': 2, 'green': 3, 'blue': 1} |
Újabb
Régebbi