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

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


当前回答

这是一个老问题,但我看到的一些答案实际上并不能工作,因为zip是不可编写脚本的。其他答案没有费心导入operator,并在这里提供关于这个模块及其好处的更多信息。

对于这个问题,至少有两个好的习语。从您提供的示例输入开始:

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

使用“装饰-排序-取消装饰”成语

这也被称为schwartzan_transform,得名于R. Schwartz,他在90年代在Perl中推广了这种模式:

# Zip (decorate), sort and unzip (undecorate).
# Converting to list to script the output and extract X
list(zip(*(sorted(zip(Y,X)))))[1]                                                                                                                       
# Results in: ('a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g')

注意,在本例中Y和X是按字典顺序排序和比较的。也就是说,比较第一项(来自Y);如果它们相同,则比较来自X的第二项,依此类推。这可能会创建不稳定的输出,除非您包含字典顺序的原始列表索引,以保持副本的原始顺序。

使用operator模块

这使您可以更直接地控制如何对输入进行排序,因此您可以通过简单地声明排序所依据的特定键来获得排序稳定性。点击这里查看更多示例。

import operator    

# Sort by Y (1) and extract X [0]
list(zip(*sorted(zip(X,Y), key=operator.itemgetter(1))))[0]                                                                                                 
# Results in: ('a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g')

其他回答

另一种选择,结合了几个答案。

zip(*sorted(zip(Y,X)))[1]

为了在python3中工作:

list(zip(*sorted(zip(B,A))))[1]

我创建了一个更通用的函数,它根据另一个列表对两个以上的列表进行排序,灵感来自@Whatang的答案。

def parallel_sort(*lists):
    """
    Sorts the given lists, based on the first one.
    :param lists: lists to be sorted

    :return: a tuple containing the sorted lists
    """

    # Create the initially empty lists to later store the sorted items
    sorted_lists = tuple([] for _ in range(len(lists)))

    # Unpack the lists, sort them, zip them and iterate over them
    for t in sorted(zip(*lists)):
        # list items are now sorted based on the first list
        for i, item in enumerate(t):    # for each item...
            sorted_lists[i].append(item)  # ...store it in the appropriate list

    return sorted_lists

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

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中的项都将被忽略,因为算法不知道要使用的排序顺序。

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

list_a = ['foo', 'bar', 'baz']
list_b = ['baz', 'bar', 'foo']
sorted(list_b, key=lambda x: list_a.index(x))
# ['foo', 'bar', 'baz']
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)))