根据另一个列表中的值对列表进行排序

根据另一个列表中的值对列表进行排序

问题描述:

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

I have a list of strings like this:

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

使用Y中的值对X进行排序以获取以下输出的最短方法是什么?

What is the shortest way of sorting X using values from Y to get the following output?

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

具有相同键"的元素的顺序无关紧要.我可以使用 for 构造,但是我很好奇是否有更短的方法.有什么建议吗?

The order of the elements having the same "key" does not matter. I can resort to the use of for constructs but I am curious if there is a shorter way. Any suggestions?

最短的代码

[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])]

说明:

  1. zip 这两个列表 s.
  2. 使用
  1. zip the two lists.
  2. create a new, sorted list based on the zip using sorted().
  3. using a list comprehension extract the first elements of each pair from the sorted, zipped list.

有关一般如何设置\使用 key 参数以及 sorted 函数的更多信息,请查看这个.

For more information on how to set\use the key parameter as well as the sorted function in general, take a look at this.