问题
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?
回答1:
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]
回答2:
If I have understood your question correctly, you can use numpy argsort and bypass the need for "second".
Here's a code snippet.
from pprint import pprint
import numpy
def main():
first= [(11.373,0.354,6.154),(22.354,0.656,0.664),(33.654,33.546,31.131)]
index_array= (numpy.argsort(first))
for i in index_array:
pprint(i.tolist())
if __name__== "__main__":
main()
Output:
[1, 2, 0]
[1, 2, 0]
[2, 1, 0]
Remember index_array contains the indexes into the original list so that if you use them in that order applied to the original list, the list is sorted.
回答3:
You can use index again to get the index in the original list, but (a) this might fail if there are duplicate elements, and (b) this has O(n²), twice. Instead, I'd suggest using enumerate(first) for first mapping elements to their indices, and then sorting the (index, element) pairs from enumerate(second), using the indices from that map as a key, to get the sorted indices from second.
>>> ind = {x: i for i, x in enumerate(first)}
>>> [i for i, x in sorted(enumerate(second), key=lambda t: ind[t[1]])]
[2, 0, 1]
回答4:
This will help:
sorted(range(len(second)),key=second.__getitem__)
also to get both item and index
sorted_indices, sorted_items = zip(*sorted([(i,e) for i,e in enumerate(second)], key=lambda x:x[1]))
来源:https://stackoverflow.com/questions/56020701/sort-python-list-by-order-of-another-list-and-retrieve-old-index