给定一个无序列表,例如
a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2]
我怎样才能获得列表中出现的每个值的频率,就像这样?
# `a` has 4 instances of `1`, 4 of `2`, 2 of `3`, 1 of `4,` 2 of `5` b = [4, 4, 2, 1, 2] # expected output
要获取无序列表中每个唯一值的频率a,您可以collections.Counter计算
a
collections.Counter
from collections import Counter a = [ a 5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2] # Count occurrences of each element count_dict = Counter(a) count_dict = Count count_dict coun # Extract frequencies into a list b = [count_dict[val] b = [count_dict[val] fo b = [count_dict[ b = [coun for val in sorted(count_dict)] pri print(b) # Output: [4, 4, 2, 1, 2]
Counter(a)
sorted(count_dict)
count_dict
Counter
[count_dict[val] for val in sorted(count_dict)]
b
a这种方法可确保您以有序的方式获取每个唯一值的频率,如预期输出中所指定的那样。