我的下面的功能是获取值列表并返回重复计数。我设法让它计数和打印,但我的任务是将其作为字典返回。我一直在努力以正确的格式返回,有什么建议吗?
def counts(values):
d = {}
for val in values:
d.setdefault(val,0)
d[val] += 1
for val, count in d.items():
d = ("{} {}".format(val,count))
return d
counts([1,1,1,2,3,3,3,3,5]) # Should return → {1: 3, 2: 1, 3: 4, 5: 1}
答案 0 :(得分:1)
只需返回创建的字典:
def counts(values):
d = {}
for val in values:
d.setdefault(val,0)
d[val] += 1
return d
收率:
>>> counts([1,1,1,2,3,3,3,3,5])
{1: 3, 2: 1, 3: 4, 5: 1}
当然,正如摩西指出的那样,Counter
是为此而建的,所以只需使用它:
from collections import Counter
def counts(values):
return dict(Counter(values))