我有一个字符串列表,像这样:
X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1 ]
使用Y中的值对X进行排序以得到以下输出的最短方法是什么?
["a", "d", "h", "b", "c", "e", "i", "f", "g"]
具有相同“键”的元素的顺序并不重要。我可以使用for结构,但我很好奇是否有更短的方法。有什么建议吗?
我有一个字符串列表,像这样:
X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1 ]
使用Y中的值对X进行排序以得到以下输出的最短方法是什么?
["a", "d", "h", "b", "c", "e", "i", "f", "g"]
具有相同“键”的元素的顺序并不重要。我可以使用for结构,但我很好奇是否有更短的方法。有什么建议吗?
当前回答
另外,如果你不介意使用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]
我在这里找到的: http://scienceoss.com/sort-one-list-by-another-list/
其他回答
你可以创建一个pandas Series,使用主列表作为数据,另一个列表作为索引,然后根据索引进行排序:
import pandas as pd
pd.Series(data=X,index=Y).sort_index().tolist()
输出:
['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']
Zip,按第二列排序,返回第一列。
zip(*sorted(zip(X,Y), key=operator.itemgetter(1)))[0]
另外,如果你不介意使用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]
我在这里找到的: http://scienceoss.com/sort-one-list-by-another-list/
我认为原题的题目不准确。如果你有两个条目数量相同的列表,并且列表1中的每个条目都以相同的顺序与列表2相关(例如a = 0, b = 1,等等),那么问题应该是“如何对字典排序?”',而不是'如何根据另一个列表的值对列表进行排序?'。在这种情况下,下面的解决方案是最有效的:
X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1 ]
dict1 = dict(zip(X,Y))
result = sorted(dict1, key=dict1.get)
print(result)
结果:
['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']
这个函数应该适用于数组。
def sortBoth(x,y,reverse=False):
'''
Sort both x and y, according to x.
'''
xy_sorted=array(sorted(zip(x,y),reverse=reverse)).T
return xy_sorted[0],xy_sorted[1]