python 进阶(15) -- 字典计数优化

[HTML_REMOVED] [HTML_REMOVED][HTML_REMOVED][HTML_REMOVED] [HTML_REMOVED][HTML_REMOVED][HTML_REMOVED]若是不相见,心中难免有牵挂[HTML_REMOVED][HTML_REMOVED][HTML_REMOVED] [HTML_REMOVED]缘由[HTML_REMOVED] [HTML_REMOVED]在需要使用python进行数据处理的地方,经常需要使用字典来进行计数,如下:[HTML_REMOVED] [HTML_REMOVED][HTML_REMOVED][HTML_REMOVED][HTML_REMOVED]city = [[HTML_REMOVED]Guangzhou[HTML_REMOVED],[HTML_REMOVED]Shanghai[HTML_REMOVED],[HTML_REMOVED]Tianjin[HTML_REMOVED],[HTML_REMOVED]Guangzhou[HTML_REMOVED],[HTML_REMOVED]Beijing[HTML_REMOVED]]

dic = {}

for c in city: if c not in dic: dic[c] = 1 else: dic[c] += 1
[HTML_REMOVED][HTML_REMOVED]

[HTML_REMOVED] [HTML_REMOVED]改进[HTML_REMOVED] [HTML_REMOVED]在网上看到一个更为简单的方法,直接使用字典的 get 方法直接精简代码[HTML_REMOVED] [HTML_REMOVED][HTML_REMOVED][HTML_REMOVED][HTML_REMOVED]city = [[HTML_REMOVED]Guangzhou[HTML_REMOVED],[HTML_REMOVED]Shanghai[HTML_REMOVED],[HTML_REMOVED]Tianjin[HTML_REMOVED],[HTML_REMOVED]Guangzhou[HTML_REMOVED],[HTML_REMOVED]Beijing[HTML_REMOVED]]

dic = {}

for c in city: dic[c] = dic.get(c,0) + 1 [HTML_REMOVED][HTML_REMOVED]

[HTML_REMOVED]

[HTML_REMOVED]