简体   繁体   中英

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

The answer I'm looking for is: [('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.

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. Then you sort about the two indeces, and you use the external comprehension to go back to the original form.

you can use sorted function, just like below.

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

the order of keys is (Y based number, X based character).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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