简体   繁体   English

如何按照与 Python 中另一个列表相同的顺序对列表进行排序?

[英]How do I sort a list in the same order as another list in Python?

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:假设我有两个列表,第一个代表总体积,第二个代表各自的唯一项目 ID,其数量等于总体积:

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.例如,50 是 ID 为 1,2 和 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.我目前正在将列表a从小到大排序,但我也想安排列表b的顺序以匹配其总容量。 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进行排序,我正在写:

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.但我不确定在 Python 中为列表b编写代码以基于相同的模式进行排序。 I have to keep the same data structure, so both lists a and b must stay a list and list of lists, respectively.我必须保持相同的数据结构,所以列表ab必须分别保持列表和列表的列表。

You can zip the two lists together, sort the tuples based on the a value, and then unzip:你可以将两个列表放在一起 zip,根据a值对元组进行排序,然后解压:

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: Output:

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

You can use zip() and two list comprehensions:您可以使用zip()和两个列表理解:

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]]

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

相关问题 如何将一个列表中的所有整数添加到另一个列表中的整数,并在Python中以相同的顺序使用不同的长度? - How do I add all integers in one list to integers on another list with different length in the same order in Python? 如何在python中以完全相同的顺序对2个列表进行排序 - How to sort 2 list in the exact same order in python 如何在 Python 中按顺序将列表元素添加到另一个列表? - How do I add list elements to another list with an order in Python? 按另一个较大列表的顺序对python列表进行排序 - Sort python list with order of another, larger list 如何在Python中保持列表中排序数字的顺序相同 - How do I keep the order of sorted numbers in a list the same in Python 如何检查列表 (list_1) 是否包含与另一个列表 (list_2) 以相同顺序排列的相同元素? - How do I check if a list (list_1) contains the same elements located in same order of another list (list_2)? 如何在给定具有所需顺序的ID列表的情况下对python的字典列表进行排序? - how do I sort a python list of dictionaries given a list of ids with the desired order? 我如何在python中对列表进行排序 - how do I sort list in python 如何在 Python 中对压缩列表进行排序? - How do I sort a zipped list in Python? 我如何检查一个列表是否以相同的顺序在另一个列表中? - How would I check if a list is in another list in the same order?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM