根据另一个列表中的值对列表进行排序 [英] Sorting list based on values from another list
本文介绍了根据另一个列表中的值对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的字符串列表:
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])]
说明:
-
zip
这两个列表
s. 使用
zip
the twolist
s.- create a new, sorted
list
based on thezip
usingsorted()
. - 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.
这篇关于根据另一个列表中的值对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文