make new python lists with indexes from items in a single list -


i want take list, e.g. [0, 1, 0, 1, 2, 2, 3], , make list of lists of (index + 1) each of unique elements. above, example, [[1, 3], [2, 4], [5, 6], [7]].

right solution ultimate in clunkiness:

list_1 = [0, 1, 0, 1, 2, 2, 3] maximum = max(list_1) master = [] in range(maximum + 1):     temp_list = []     j,k in enumerate(list_1):         if k == i:             temp_list.append(j + 1)     master.append(temp_list) print master 

any thoughts on more pythonic way appreciated!

i in 2 steps:

  1. build map {value: [list, of, indices], ...}:

    index_map = {} index, value in enumerate(list_1):     index_map.setdefault(value, []).append(index+1) 
  2. extract value lists dictionary master list:

    master = [index_map.get(index, []) index in range(max(index_map)+1)] 

for example, give:

>>> index_map {0: [1, 3], 1: [2, 4], 2: [5, 6], 3: [7]} >>> master [[1, 3], [2, 4], [5, 6], [7]] 

this implementation iterates on whole list once (o(n), n len(list_1)) whereas others far iterate on whole list once for each unique element (o(n*m), m len(set(list_1))). taking max(d) rather max(list_1) need iterate on length of unique items, more efficient.

the implementation can simpler if make d = collections.defaultdict(list).


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

c# - two queries in same method -