Trying to retrieve the index of sorted list "second".
"second" contains same values as "first" and will be reordered to become identical order as "first". I'm looking for an indexlist "d" which contains the the reordered indexes from old "second".
tryied to retrieve "d" with zip or enumerate, but failed.
first= [(11.373,0.354,6.154),(22.354,0.656,0.664),(33.654,33.546,31.131)]
second=[(22.354,0.656,0.664),(33.654,33.546,31.131),(11.373,0.354,6.154)]
second=sorted(second,key=first.index)
print(first)
print(second)
[(11.373, 0.354, 6.154), (22.354, 0.656, 0.664), (33.654, 33.546, 31.131)]
[(11.373, 0.354, 6.154), (22.354, 0.656, 0.664), (33.654, 33.546, 31.131)]
Here "second" become same order as "first". Cool.
But how can I retrieve the reorderd Indexlist "d" from "second"?
I tried like:
d = [i[0] for i in sorted(enumerate(second), key=first.index)]
In this example "d" should become [2,0,1]
This type of key is somehow blocking the possibility to retriev the old index. Any recommendation?
解决方案
This is one approach.
Ex:
first= [(11.373,0.354,6.154),(22.354,0.656,0.664),(33.654,33.546,31.131)]
second=[(22.354,0.656,0.664),(33.654,33.546,31.131),(11.373,0.354,6.154)]
temp = sorted(second,key=first.index) #Sorted List.
d = list(map(lambda x: second.index(x), temp)) #Fetch index from temp
print(first)
print(temp)
print(d)
Output:
[(11.373, 0.354, 6.154), (22.354, 0.656, 0.664), (33.654, 33.546, 31.131)]
[(11.373, 0.354, 6.154), (22.354, 0.656, 0.664), (33.654, 33.546, 31.131)]
[2, 0, 1]