简体   繁体   English

按给定顺序重新排序列表

[英]Reordering a list in a given order

I want to reorder my list in a given order, For example I have a list of ['a', 'b', 'c', 'd', 'e', 'f', 'g'] this has an index of [0,1,2,3,4,5,6] and lets say the new ordered list would have an order of [3,5,6,1,2,4,0] which would result in ['d','f','g', 'b', 'c', 'e', 'a'].我想以给定的顺序重新排序我的列表,例如我有一个 ['a', 'b', 'c', 'd', 'e', 'f', 'g'] 列表,它有一个[0,1,2,3,4,5,6] 的索引,假设新的有序列表将具有 [3,5,6,1,2,4,0] 的顺序,这将导致 [' d'、'f'、'g'、'b'、'c'、'e'、'a']。

How would you result in such code?你会如何产生这样的代码?

I thought of using for loop by doing the我想通过执行以下操作来使用 for 循环

 for i in range(Len(list))

and after that I thought go using append or creating a new list?之后我想使用附加或创建一个新列表? maybe but I'm not sure if I'm approaching this right.也许,但我不确定我是否正在接近这一点。

All you need to do is iterate the list of indexes, and use it to access the list of elements, like this:您需要做的就是迭代索引列表,并使用它来访问元素列表,如下所示:

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

result = [elems[i] for i in idx]
print(result)

Output:输出:

['d', 'f', 'g', 'b', 'c', 'e', 'a']
import numpy as np

my_list =  ['a', 'b', 'c', 'd', 'e', 'f', 'g']

def my_function(my_list, index):
    return np.take(my_list, index)

print(my_function(my_list, [3,5,6,1,2,4,0]))

Output: ['d' 'f' 'g' 'b' 'c' 'e' 'a']

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

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