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

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


当前回答

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)

其他回答

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

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]

Zip,按第二列排序,返回第一列。

zip(*sorted(zip(X,Y), key=operator.itemgetter(1)))[0]

我认为如果两个列表的大小不同或包含不同的项目,上面的大多数解决方案都是无效的。下面的解决方案很简单,应该可以解决这些问题:

import pandas as pd

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

result = pd.merge(pd.DataFrame(list1), pd.DataFrame(list2))
print(list(result[0]))

输出:

['A', 'C']

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

实际上,我来这里是为了对值匹配的列表进行排序。

list_a = ['foo', 'bar', 'baz']
list_b = ['baz', 'bar', 'foo']
sorted(list_b, key=lambda x: list_a.index(x))
# ['foo', 'bar', 'baz']

你可以创建一个pandas Series,使用主列表作为数据,另一个列表作为索引,然后根据索引进行排序:

import pandas as pd
pd.Series(data=X,index=Y).sort_index().tolist()

输出:

['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']