Convert list to another form but providing same information

Paul Rubin no.email at nospam.invalid
Mon Mar 21 21:35:12 EDT 2016


Maurice <mauricioliveiraguarda at gmail.com> writes:
> I have a list such [6,19,19,21,21,21]
> Therefore the resulting list should be:
> [0,0,0,0,0,0,1,0,0,0...,2,0,3,0...0]

Rather than a sparse list you'd typically want a dictionary (untested):

  from collections import defaultdict
  the_list = [0,0,0,0,0,0,1,0,0,0...,2,0,3,0...0]
  ...
  days = defaultdict(int)
  for t in the_list:
     days[t] += 1

this results in days being the defaultdict { 6:1, 19:2, 21:3 }.

defaultdict is a special type of dictionary where if you try to access a
non-existent element, it gets created and initialized with the data
constructor you made it with.  In this case the data constructor is int,
and int() makes the number 0, so the defaultdict elements are
initialized to 0.



More information about the Python-list mailing list