根据另一个列表中的值对列表进行排序? [英] Sorting list based on values from another list?

查看:112
本文介绍了根据另一个列表中的值对列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 这两个list.
  2. 使用zip创建一个新的,已排序的list. > sorted() .
  3. 使用列表理解提取从已排序的压缩后的list中提取每对中的第一个元素.
  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.

这篇关于根据另一个列表中的值对列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆