python对两个列表进行排序 [英] python sorting two lists

查看:74
本文介绍了python对两个列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将两个列表排序在一起:

I am trying to sort two lists together:

list1 = [1, 2, 5, 4, 4, 3, 6]
list2 = [3, 2, 1, 2, 1, 7, 8]

list1, list2 = (list(x) for x in zip(*sorted(zip(list1, list2))))

无论如何,这样做使我获得了输出

Anyway, doing this gives me on output

list1 = [1, 2, 3, 4, 4, 5, 6]
list2 = [3, 2, 7, 1, 2, 1, 8]

同时我想在第一个列表中将初始顺序保持等于4:我想要的是

while I would want to keep the initial order for equal number 4 in the first list: what I want is

list1 = [1, 2, 3, 4, 4, 5, 6]
list2 = [3, 2, 7, 2, 1, 1, 8]

我该怎么办?我不想使用循环进行气泡排序.任何帮助表示赞赏.

What do I have to do? I wouldn't want to use loop for bubble-sorting. Any help appreciated.

推荐答案

对您的排序使用key参数,该参数仅比较该对中的第一个元素.由于Python的排序是稳定的,因此可以保证当第一个元素相等时,第二个元素的顺序将保持不变.

Use a key parameter for your sort that only compares the first element of the pair. Since Python's sort is stable, this guarantees that the order of the second elements will remain the same when the first elements are equal.

>>> from operator import itemgetter
>>> [list(x) for x in zip(*sorted(zip(list1, list2), key=itemgetter(0)))]
[[1, 2, 3, 4, 4, 5, 6], [3, 2, 7, 2, 1, 1, 8]]

等同于:

>>> [list(x) for x in zip(*sorted(zip(list1, list2), key=lambda pair: pair[0]))]
[[1, 2, 3, 4, 4, 5, 6], [3, 2, 7, 2, 1, 1, 8]]

这篇关于python对两个列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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