Home > Software engineering >  How do I sort a list in the same order as another list in Python?
How do I sort a list in the same order as another list in Python?

Time:04-02

Let's say I have two lists with the first representing total volume and the second representing the respective unique item IDs whose volume is equal to the total volume:

a = [50, 45, 90, 75]

b = [[1,2,3], [5,6,7], [4], [8,9]]

For example, 50 would be the total volume of the items with the IDs of 1,2, and 3.

I am currently sorting list a to be from smallest to largest, but I also want to arrange the order of list b to match its total volume. Based on the previously made lists, I want both lists to sort like this:

a = [45, 50, 75, 90]

b = [[5,6,7], [1,2,3], [8,9], [4]]

To sort list a, I am writing:

a.sort(key=lambda x: x, reverse = False)

But I'm not sure write the code in Python for list b to sort based on the same pattern. I have to keep the same data structure, so both lists a and b must stay a list and list of lists, respectively. Could anyone tell me how to solve this issue?

CodePudding user response:

You can zip the two lists together, sort the tuples based on the a value, and then unzip:

a = [45, 50, 75, 90]
b = [[5,6,7], [1,2,3], [8,9], [4]]

a,b = map(list, zip(*sorted(zip(a, b), key = lambda x: x[0])))

print(a, b, sep='\n')

Output:

[45, 50, 75, 90]
[[5, 6, 7], [1, 2, 3], [8, 9], [4]]

CodePudding user response:

You can use zip() and two list comprehensions:

a = [50, 45, 90, 75]
b = [[1,2,3], [5,6,7], [4], [8,9]]

a = [x for x, _ in sorted(zip(a, b))]
b = [y for _, y in sorted(zip(a, b))]
print(a)
print(b)

This outputs:

[45, 50, 75, 90]
[[5, 6, 7], [1, 2, 3], [8, 9], [4]]
  • Related