Home > OS >  Need take indices from list in specific order
Need take indices from list in specific order

Time:10-21

I have some list A = ['a', 'b', 'c', 'd', 'e', 'f'] I need take indices of elements in this order 0 1 1 2 2 3 3 4 4 5

But my code made this order 0 1 2 3 4 5

A = ['a', 'b', 'c', 'd', 'e', 'f']
for i in A:
    print(A.index(i), end=' ')

CodePudding user response:

If you have the desired indices why not try this:

X = [0, 1, 1, 2, 2, 3, 3, 4, 4, 5]
A = ['a', 'b', 'c', 'd', 'e', 'f']
for i in X:
    print(A[i], end=' ')

CodePudding user response:

Using list comprehension to extract the values corresponding to the indices.

X = [0, 1, 1, 2, 2, 3, 3, 4, 4, 5]
A = ['a', 'b', 'c', 'd', 'e', 'f'] 
new_list = [A[x] for x in X]

Update

list_of_list = [[x,x] for x in range(1,len(A))]

new_list = [0] [item for sublist in list_of_list for item in sublist]
  • Related