如何在 Python 中根据第一个列表和另一个列表对两个列表进行排序? [英] How to sort two lists based on one first and the other next in Python?

查看:77
本文介绍了如何在 Python 中根据第一个列表和另一个列表对两个列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要并行排序两个列表,先按一个列表排序,然后对具有相同值的元素按第二个列表排序的方法是什么?任何一个列表都可能有重复的元素.

To sort two lists in parallel, what's the way of sorting by one list first, then for elements with the same value, sorting by the second list? Either list could have duplicated elements.

list_a = [3,2,4,4,5]
list_b = ['d','b','a','c','b']

输出需要根据(1)list_a中的值从大到小,以及(2)list_a中具有相同值的元素,在list_b中按字母顺序排序.

The output needs to be based on (1) the value from list_a from the largest to the smallest, and (2) for elements with the same value in list_a, sort by alphabetical order in list_b.

list_a = [5,4,4,3,2]
list_b = ['b','a','c','d','b']

有什么想法吗?

推荐答案

配对、排序、取消配对、回写:

Pair, sort, unpair, write back:

list_a[:], list_b[:] = zip(*sorted(zip(list_a, list_b), key=lambda p: (-p[0], p[1])))

回写可以保持简短并对现有列表对象进行排序,而不是单独的新对象.

Writing back keeps it short and sorts the existing list objects rather than having separate new ones.

更多垂直版本,可能更好:

More vertical version, probably nicer:

pairs = list(zip(list_a, list_b))
pairs.sort(key=lambda p: (-p[0], p[1]))
list_a[:], list_b[:] = zip(*pairs)

这篇关于如何在 Python 中根据第一个列表和另一个列表对两个列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆