Home > Back-end >  how to sort a list of tuples based on another list
how to sort a list of tuples based on another list

Time:12-15

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.

CodePudding user response:

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.

CodePudding user response:

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).

  • Related