简体   繁体   English

如何根据另一个列表对元组列表进行排序

[英]how to sort a list of tuples based on another list

X = ["v", "g", "r", "a", "f"]
Y = [("v", 7), ("f", 3), ("r", 3), ("g", 7), ("a", 2)]

I want to first sort the list Y based on the numbers in ascending order, and then sort the sorted Y based on the letters in X我想先根据数字升序对列表 Y 进行排序,然后根据 X 中的字母对排序后的 Y 进行排序

The answer I'm looking for is: [('a', 2), ('r', 3), ('f', 3), ('v', 7), ('g', 7)]我正在寻找的答案是: [('a', 2), ('r', 3), ('f', 3), ('v', 7), ('g', 7)]

  1. sorting numbers in ascending order.按升序排列数字。
  2. the number of 'r' and 'f' is 3, I want to sort them based on X, first r then f. 'r' 和 'f' 的数量是 3,我想根据 X 对它们进行排序,首先是 r,然后是 f。

Just using list comprehensions:仅使用列表推导:

Y = [(x, y) for x, y, _ in sorted([(x, y, X.index(x)) for x, y in Y], key=lambda x: x[1:])]

In the internal comprehension, you had a third number to each element in Y - the index in x.在内部理解中,Y 中的每个元素都有第三个数字——x 中的索引。 Then you sort about the two indeces, and you use the external comprehension to go back to the original form.然后对这两个索引进行排序,然后使用外部理解将 go 恢复为原始形式。

you can use sorted function, just like below.您可以使用sorted的 function,如下所示。

sorted(Y, key=lambda a: (a[1], X.index(a[0])))

the order of keys is (Y based number, X based character).键的顺序是(基于 Y 的数字,基于 X 的字符)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM