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

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


当前回答

下面是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是元组。 我也在想是否有更好的方法来做到这一点。

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

其他回答

下面是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是元组。 我也在想是否有更好的方法来做到这一点。

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

上面的大多数解决方案都很复杂,我认为如果列表的长度不同或不包含完全相同的项目,它们就不会起作用。下面的解决方案很简单,不需要任何导入。

list1 = ['B', 'A', 'C']  # Required sort order
list2 = ['C', 'B']       # Items to be sorted according to list1

result = list1
for item in list1:
    if item not in list2: result.remove(item)

print(result)

输出:

['B', 'C']

注意:任何不在list1中的项都将被忽略,因为算法不知道要使用的排序顺序。

另外,如果你不介意使用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']
list1 = ['a','b','c','d','e','f','g','h','i']
list2 = [0,1,1,0,1,2,2,0,1]

output=[]
cur_loclist = []

获取list2中的唯一值

list_set = set(list2)

查找list2中索引的loc

list_str = ''.join(str(s) for s in list2)

索引在list2中的位置使用cur_loclist跟踪

[0, 3, 7, 1, 2, 4, 8, 5, 6]

for i in list_set:
cur_loc = list_str.find(str(i))

while cur_loc >= 0:
    cur_loclist.append(cur_loc)
    cur_loc = list_str.find(str(i),cur_loc+1)

print(cur_loclist)

for i in range(0,len(cur_loclist)):
output.append(list1[cur_loclist[i]])
print(output)