1

Suppose I have a list

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

This list can contain (repeating) numbers from 0 to n (here n=4). Can I generate a list using list comprehension, where the value at index is equal to the count of that number in list a For e.g., output list in above scenario would be

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

Explanation

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
inferno
  • 55
  • 5

2 Answers2

1

You could use 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. do not use input as a variable name, this is a python builtin

output:

[0, 2, 7, 4, 2]
mozway
  • 194,879
  • 13
  • 39
  • 75
0
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])
d.b
  • 32,245
  • 6
  • 36
  • 77