简体   繁体   English

有没有python方法根据提供的新索引重新排序列表?

[英]Is there a python method to re-order a list based on the provided new indices?

Say I have a working list: ['a','b','c'] and an index list [2,1,0] which will change the working list to: ['c','b','a'] 假设我有一个工作清单:['a','b','c']和索引列表[2,1,0],它会将工作清单更改为:['c','b','a “]

Is there any python method to do this easily (the working list may also be a numpy array, and so a more adaptable method is greatly preferred)? 是否有任何python方法可以轻松完成此任务(工作列表也可能是一个numpy数组,因此更适合使用更具适应性的方法)? Thanks! 谢谢!

  • ordinary sequence: 普通顺序:

     L = [L[i] for i in ndx] 
  • numpy.array : numpy.array

     L = L[ndx] 

Example: 例:

>>> L = "abc"
>>> [L[i] for i in [2,1,0]]
['c', 'b', 'a']

Converting my comment-answer from when this question was closed: 从关闭此问题时转换我的评论答案:

As you mentioned numpy, here is an answer for that case: 正如你提到的numpy,这是这种情况的答案:

For numerical data , you can do this directly with numpy arrays Details here: http://www.scipy.org/Cookbook/Indexing#head-a8f6b64c733ea004fd95b47191c1ca54e9a579b5 对于数值数据 ,您可以直接使用numpy数组执行此操作详细信息: http//www.scipy.org/Cookbook/Indexing#head-a8f6b64c733ea004fd95b47191c1ca54e9a579b5

the syntax is then 然后是语法

myarray[myindexlist]

For non-numerical data , the most efficient way in the case of long arrays which you read out only once is most likely this: 对于非数值数据 ,在只读出一次的长数组的情况下最有效的方法很可能是:

(myarray[i] for i in myindex) 

note the () for generator expressions instead of [] for list comprehension. 注意生成器表达式的()而不是列表推导的[]。

Read this: Generator Expressions vs. List Comprehension 阅读本文: 生成器表达式与列表理解

This is very easy to do with numpy if you don't mind converting to numpy arrays: 如果您不介意转换为numpy数组,那么使用numpy非常容易:

>>> import numpy
>>> vals = numpy.array(['a','b','c'])
>>> idx = numpy.array([2,1,0])
>>> vals[idx]
array(['c', 'b', 'a'], 
      dtype='|S1')

To get back to a list, you can do: 要返回列表,您可以执行以下操作:

>>> vals[idx].tolist()
['c', 'b', 'a']

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

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