Create a list from another list indexes

时间:2018-03-25 19:01:51

标签: python list indexing

Is there a pythonic way to create a list from indexes of another list? Iam trying to create a list from indexes of another one. I read that enumerate() can be used to iterate through both index and values of a given list. But don't really know how to apply that in my case.

In my case the procedure looks like this:

list_1 = [11,10,7,0,3,5,8,1,4,6,9,2]

The second list should contain the indexes of the first one but from the next index except from the index 0. For example for index 0 in list_1 which contains the value 11 the next value would be 12 but it does not exist in the list_1 so the next value is 0 which actually is the smallest value, so the value for index 0 in list_2 would be the index of list_1 which contains the value 0, in this case would be 3. For the index 1 in list_1 the value is 10 so the value for index 1 in list_2 would be the index which contains the value 11 (10+1), in this case 0. As a result the list_2 is:

list_2 =[3,0,6,7,8,9,10,11,5,2,1,4]

2 个答案:

答案 0 :(得分:0)

This snippet should do what you are asking for (in a pythonic/explicit way):

list_1 = [11, 10, 7, 0, 3, 5, 8, 1, 4, 6, 9, 2]

# keep the indexes of every element
indexes = {v: idx for idx, v in enumerate(list_1)}
# return the index of every next element - if there isn't, return the index for 0
list_2 = [indexes.get(v+1, indexes[0]) for v in list_1]

答案 1 :(得分:0)

Or, you can use the index() method to retrieve the index of each element + 1:

[list_1.index(e+1) if e+1 in list_1 else list_1.index(0) for e in list_1]