我有一个字符串列表,像这样:

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结构,但我很好奇是否有更短的方法。有什么建议吗?


当前回答

这个函数应该适用于数组。

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]

其他回答

X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0,   1,   1,   0,   1,   2,   2,   0,   1 ]

你可以用一行写出来:

X, Y = zip(*sorted(zip(Y, X)))

下面是Whatangs的答案,如果你想获得两个排序的列表(python3)。

X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0,   1,   1,    0,   1,   2,   2,   0,   1]

Zx, Zy = zip(*[(x, y) for x, y in sorted(zip(Y, X))])

print(list(Zx))  # [0, 0, 0, 1, 1, 1, 1, 2, 2]
print(list(Zy))  # ['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']

记住Zx和Zy是元组。 我也在想是否有更好的方法来做到这一点。

警告:如果你用空列表运行它,它会崩溃。

把两个列表压缩在一起,排序,然后取你想要的部分:

>>> yx = zip(Y, X)
>>> yx
[(0, 'a'), (1, 'b'), (1, 'c'), (0, 'd'), (1, 'e'), (2, 'f'), (2, 'g'), (0, 'h'), (1, 'i')]
>>> yx.sort()
>>> yx
[(0, 'a'), (0, 'd'), (0, 'h'), (1, 'b'), (1, 'c'), (1, 'e'), (1, 'i'), (2, 'f'), (2, 'g')]
>>> x_sorted = [x for y, x in yx]
>>> x_sorted
['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']

把这些结合起来得到:

[x for y, x in sorted(zip(Y, X))]

这个函数应该适用于数组。

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]

另外,如果你不介意使用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/