0

For example say we have a list of numbers

[0, 0, 4, 7, 3, 3, 7, 7, 7, 9]

0 occurs twice, however 1 & 2 do not occur, but then 3 occurs twice, so on and so forth.

Is there a built in function that would give me

[2, 0, 0, 2, 1, 0, 0, 4, 0, 1]  

If not how could I go about incorporating zeros for values that do not occur?

ORM
  • 25
  • 1
  • 4
  • Briefly: `collections.Counter`. – TigerhawkT3 Nov 28 '16 at 01:55
  • 1
    @TigerhawkT3 `collections.Counter` won't entirely trivially work if you want zeroes in your counts. – miradulo Nov 28 '16 at 01:57
  • This isn't the same question as the one it's been marked as duplicate of. The OP wants to see zeros too, which `Counter` doesn't to on its own. – Batman Nov 28 '16 at 02:02
  • @Mitch - Make a `collections.Counter` and try to retrieve an element that isn't in it: you will get a value of zero. – TigerhawkT3 Nov 28 '16 at 02:05
  • @TigerhawkT3 I'm well aware, and you could form a simple list comprehension. I'm just saying it's not exactly a duplicate (the zeros in particular seem to be what the OP is hung up on) - your call I suppose. – miradulo Nov 28 '16 at 02:05
  • @Mitch - It's an [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). OP is only looking for a list that produces equivalent values for each index because they didn't know about `collections.Counter`. – TigerhawkT3 Nov 28 '16 at 02:07
  • @TigerhawkT3 Fair enough, I trust your judgement. – miradulo Nov 28 '16 at 02:12
  • `>>> import collections >>> >>> clist=[0, 0, 4, 7, 3, 3, 7, 7, 7, 9] >>> >>> counter = collections.Counter(clist) >>> counter Counter({7: 4, 0: 2, 3: 2, 9: 1, 4: 1}) >>> counter_list=[] >>> for key,values in counter.items(): ... counter_list.append(values) ... >>> counter_list [2, 1, 2, 1, 4]` – Vibhutha Kumarage Nov 28 '16 at 03:11

0 Answers0