运行结果:
{1: 1, 2: 2, 3: 1} lst=[1,2,3,2] d={} for x in lst: if x in d: d[x]+=1 else: d[x]=1 print(d)运行结果:
{1: 1, 2: 2, 3: 1} lst=[1,2,3,2] d={} for x in lst: d[x]=lst.count(x) print(d)运行结果:
{1: 1, 2: 2, 3: 1} d1={} lst=[1,2,3,3] for x in lst: d1[x]=d1.get(x,0)+1 print(d1)运行结果:
{1: 1, 2: 1, 3: 2}频次统计问题,使用collections模块的Counter类可以快速的实现这个功能。
from collections import Counter print(Counter(lst).most_common(len(lst))) #将其转换为字典类型 print(dict(Counter(lst).most_common(len(lst))))运行结果:
[(3, 2), (1, 1), (2, 1)] {3: 2, 1: 1, 2: 1}