最后活跃于 1731079542

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

kristofer's Avatar kristofer 修订了这个 Gist 1731079542. 跳至此修订

没有变更

kristofer's Avatar kristofer 修订了这个 Gist 1731079460. 跳至此修订

1 file changed, 28 insertions

dict-count.py(file created)

@@ -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}
更新 更早