在Python中使用列表推导生成一个列表,该列表给出数字的计数并将数字放在特定的索引处



假设我有一个列表

input = [4, 4, 2, 2, 2, 2, 3, 3, 3, 3, 1, 1, 2, 2, 2]

这个列表可以包含(重复的)从0到n的数字(这里n=4)。我是否可以使用列表推导生成一个列表,其中索引处的值等于列表a中该数字的计数例如,上述场景中的输出列表为

output = [0, 2, 7, 4, 2]

解释
here
output[0] = 0 #since we don't have any 0 in input list
output[1] = 2 #since we have two 1's in input list
output[2] = 7 #since we have seven 2's in input list
output[3] = 4 #since we have four 3's in input list
output[4] = 2 #since we have two 4's in input list

您可以使用collections.Counter:

from collections import Counter
inp = [4, 4, 2, 2, 2, 2, 3, 3, 3, 3, 1, 1, 2, 2, 2]
c = Counter(inp)
output = [c[k] for k in range(max(c)+1)]

NB。不要使用input作为变量名,这是python内置的

输出:

[0, 2, 7, 4, 2]
d = {}
[d.setdefault(el, []).append(1) for el in input]
[len(d.get(k, [])) for k in range(max(d.keys()) + 1)]
# [0, 2, 7, 4, 2])