Python: 计算频率

307 阅读1分钟

问题

给出一个数组, 计算每个数字的频率.

解答

字典法

for x in nums:
    hist[x] = hist.get(x, 0) + 1

print(hist)

自带数据结构collection

from collections import Counter

counter = Counter(nums)
print(counter)

# 排序后输出
print("{", end="")
for i in sorted(hist.keys()):
    print(str(i) + ": " + str(hist[i]), end=" ")
print("}")