根据另一个列表中的值排序列表?我有这样一个字符串列表: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构造,但我很好奇是否有更短的方法。有什么建议吗?
3 回答
喵喔喔
TA贡献1735条经验 获得超5个赞
最短码
[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])]
解释:
key
sorted
蝴蝶刀刀
TA贡献1801条经验 获得超8个赞
将这两个列表压缩在一起,对其进行排序,然后取您想要的部分:
>>> 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))]
添加回答
举报
0/150
提交
取消