喵喔喔
最短码[x for _,x in sorted(zip(Y,X))]例子:X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
Z = [x for _,x in sorted(zip(Y,X))]print(Z) # ["a", "d", "h", "b", "c", "e", "i", "f", "g"]一般来说[x for _, x in sorted(zip(Y,X), key=lambda pair: pair[0])]解释:zip两人listS.创建一个新的排序list基于zip使用sorted().使用列表理解提取液排序和压缩后的每对的第一个元素。list.有关如何设置\使用key参数以及sorted函数的一般情况下,请看一看这,这个.
蝴蝶刀刀
将这两个列表压缩在一起,对其进行排序,然后取您想要的部分:>>> 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))]