本文翻译自:Sorting list based on values from another list?
I have a list of strings like this: 我有一个这样的字符串列表:
X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
What is the shortest way of sorting X using values from Y to get the following output? 使用Y中的值对X进行排序以获取以下输出的最短方法是什么?
["a", "d", "h", "b", "c", "e", "i", "f", "g"]
The order of the elements having the same "key" does not matter. 具有相同“键”的元素的顺序无关紧要。 I can resort to the use of for
constructs but I am curious if there is a shorter way. 我可以求助于for
构造,但是我想知道是否有更短的方法。 Any suggestions? 有什么建议么?
#1楼
参考:https://stackoom.com/question/RlmF/根据另一个列表中的值对列表进行排序
#2楼
Another alternative, combining several of the answers. 另一个选择,结合几个答案。
zip(*sorted(zip(Y,X)))[1]
In order to work for python3: 为了使用python3:
list(zip(*sorted(zip(B,A))))[1]
#3楼
Also, if you don't mind using numpy arrays (or in fact already are dealing with numpy arrays...), here is another nice solution: 另外,如果您不介意使用numpy数组(或者实际上已经在处理numpy数组...),这是另一个不错的解决方案:
people = ['Jim', 'Pam', 'Micheal', 'Dwight']
ages = [27, 25, 4, 9]
import numpy
people = numpy.array(people)
ages = numpy.array(ages)
inds = ages.argsort()
sortedPeople = people[inds]
I found it here: http://scienceoss.com/sort-one-list-by-another-list/ 我在这里找到它: http : //scienceoss.com/sort-one-list-by-another-list/
#4楼
I like having a list of sorted indices. 我喜欢列出排序索引。 That way, I can sort any list in the same order as the source list. 这样,我可以按照与源列表相同的顺序对任何列表进行排序。 Once you have a list of sorted indices, a simple list comprehension will do the trick: 一旦有了排序索引的列表,简单的列表理解就可以解决问题:
X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
sorted_y_idx_list = sorted(range(len(Y)),key=lambda x:Y[x])
Xs = [X[i] for i in sorted_y_idx_list ]
print( "Xs:", Xs )
# prints: Xs: ["a", "d", "h", "b", "c", "e", "i", "f", "g"]
Note that the sorted index list can also be gotten using numpy.argsort()
. 请注意,也可以使用numpy.argsort()
获得排序后的索引列表。
#5楼
more_itertools
has a tool for sorting iterables in parallel: more_itertools
有一个用于并行迭代可迭代对象的工具:
from more_itertools import sort_together
sort_together([Y, X])[1]
# ('a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g')
#6楼
You can create a pandas Series
, using the primary list as data
and the other list as index
, and then just sort by the index: 您可以创建pandas Series
,使用主列表作为data
,另一个列表作为index
,然后按索引排序:
import pandas as pd
pd.Series(data=X,index=Y).sort_index().tolist()
output: 输出:
['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']