1

Suppose, I have multiple arrays in one array with the number from 0 to n in multiple order. For example,

x = [[0,2,3,5],[1,4]]

Here we have two arrays in x. There could be more than two.

I want to get rearrange all the array elements based on their number sequence. However, they will represent their array ID. The result should be like this

y = [0,1,0,0,1,0]

That means 0,2,3,5 is in array id 0. So, they will show the id in their respective sequence. Same for 1 and 4. Can anyone help me to solve this? [N.B. There could be more than two arrays. So, it will be highly appreciated if the code work for different array numbers]

2 Answers 2

2
  1. You can do this by using a dictionary
x = [[0,2,3,5],[1,4]]
lst = {}
for i in range(len(x)):
    for j in range(len(x[i])):
        lst[x[i][j]] = i
print(lst)
  1. You can also do this by using list, list.insert(idx, value) means value is inserted to the list at the idxth index. Here, we are traversing through all the values of x and the value x[i][j] is in the i th number array.
x = [[0,2,3,5],[1,4]]
lst = []
for i in range(len(x)):
    for j in range(len(x[i])):
        lst.insert(x[i][j], i)
print(lst)

Output: [0, 1, 0, 0, 1, 0]

Sign up to request clarification or add additional context in comments.

3 Comments

@Lzz0 i hope you got it
Using insert on a list is an O(n) operation since all the values that come after the insert index need to be moved down in memory every time, so it would be bad for big lists. Therefore I think you should put your dictionary solution as the first one since it will be more efficient for the OP.
@ShashSinha thanks for your comment, updated.
1

You might also consider using np.argsort for rearranging your array values and create the index-array with list comprehension:

x = [[0,2,3,5],[1,4]]
order = np.concatenate(x).argsort()
np.concatenate([ [i]*len(e) for i,e in enumerate(x) ])[order]

array([0, 1, 0, 0, 1, 0])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.