简体   繁体   English

您将如何将重新排序的列表重新排序回以前的形式?

[英]How would you re-order the reordered list back to its previous form?

element =  ['a', 'b', 'c', 'd', 'e', 'f', 'g']
index_list =  [3,5,6,1,2,4,0]

result = [element[i] for i in index_list]
print(result)

this would eventually give me a ordered list based on the index list which would give ['d', 'f', 'g', 'b', 'c', 'e', 'a'].这最终会给我一个基于索引列表的有序列表,它会给出 ['d', 'f', 'g', 'b', 'c', 'e', 'a']。

How would you re-order this already re-ordered list back to its previous form which would be ['a', 'b', 'c', 'd', 'e', 'f', 'g']?你如何将这个已经重新排序的列表重新排序回它以前的形式,即 ['a', 'b', 'c', 'd', 'e', 'f', 'g']? I tried using the given index list again but it did not returned it back, but simply gave me a new list.我再次尝试使用给定的索引列表,但它没有返回,只是给了我一个新列表。 Would there be any way I could still use the given index list to reorder the list back?有什么办法我仍然可以使用给定的索引列表来重新排序列表吗?

You can do the opposite:你可以做相反的事情:

reordered = [None] * len(result)
for index, e in zip(index_list, result):
    reordered[index] = e

You can process index_list to do the reverse permutation:您可以处理index_list进行反向排列:

index_list =  [3,5,6,1,2,4,0]    
reverse = [i for i, n in sorted(enumerate(index_list), key=lambda x: x[1])]

original = [result[i] for i in reverse]

像这样的东西

print([a for a, b in sorted(zip(result, index_list), key=lambda x: x[1])])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM