【发布时间】:2018-03-27 05:57:43
【问题描述】:
基本上我正在编写一个函数,它接收一个列表作为输入并返回一个字典,该字典计算列表中数据重复的次数。
#Example:
count_occurrences(["a", "b", "c", "a", "a," "b"])
#output:
{"a" : 3, "b" : 2, "c": 1}
到目前为止,我的解决方案是:
def count_occurrences(a_list):
count_list = {}
for i in a_list:
if i not in count_list:
count_list[i] = 1
else:
count_list[i] += 1
return count_list
但我想知道是否有办法使用字典理解来缩短/优化这个脚本。
【问题讨论】:
标签: python python-3.x list dictionary-comprehension