0

I have been given a list of positive integer numbers upto 10^6 and total number of item in the given list will be 10** 4 at most. I want to store these values in a particular order as explained below.

I want to iterate through the list and want to place the index value of item in the inner list corresponding to that item.

Example

Given List : [3,0,1,1]

output : [[1],[2,3],[],[0]] #expected output

basically output list should contains lists with index corresponding to item value in given list which should contain index value

I have comeup with this solution.

sequence = [[]] * 4
given = [3,0,1,1]
index = 0
for num in given:
    sequence[num].append(index)
    index+=1
print(sequence)

but the output I am getting is [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]] and cannot figure out why.

Community
  • 1
  • 1
aman goyal
  • 191
  • 2
  • 14

1 Answers1

0

This will do it:

a = [3, 0, 1, 1]
[[j for j, k in enumerate(a) if k == i] for i, _ in enumerate(a)]
#[[1], [2, 3], [], [0]]
zipa
  • 27,316
  • 6
  • 40
  • 58