根据另一个列表的排序方式对列表进行排序.的Python 3 [英] Sorting a list based on how another list was sorted. Python 3

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

问题描述

一段时间以来,我一直在努力根据Python 3中的先前排序列表对列表进行排序,尽管我会寻求你们的帮助.

I've been struggling with sorting a list based on a previous sorted list in Python 3 for a while and though I would ask for help from you guys.

好,所以我有一个列表:

Ok, so I have a list:

list = ['A103', 'A101', 'C101', 'B101'] 

此列表使用以下代码先后按字母顺序和数字顺序排序:

This list is sorted in an alphabetic and then numeric way with the following code:

convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
list_sorted = sorted(list, key=alphanum_key)

新列表list_sorted如下:['A101', 'A103', 'B101', 'C101'].

The new list, list_sorted looks like this: ['A101', 'A103', 'B101', 'C101'].

到了棘手的部分,我还有另一个列表,其值与列表"中的值相对应,需要以相同的方式进行排序.

Now to the tricky part, I have another list with values corresponding to the values in "list" which need to be sorted in the same way.

示例:

list = ['A103', 'A101', 'C101', 'B101'] 

rad = ['£', '$', '€', '@']


list_sorted =['A101', 'A103', 'B101', 'C101']

rad = ['$', '£', '@', '€'].

非常感谢所有帮助,谢谢!

All help is highly appreciated, thank you!

推荐答案

请勿尝试进行两次排序.而是将两个列表压缩在一起,然后再进行排序,并且仅针对第一项进行排序.

Do not attempt to sort twice. Instead, zip both lists together before sorting and only sort with regard to the first item.

import re

list = ['A103', 'A101', 'C101', 'B101']
rad = ['£', '$', '€', '@']

convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key[0])]
#                                           only consider first item ----^

list_sorted = sorted(zip(list, rad), key=alphanum_key)
#   zip both lists ---^

print(list_sorted) # [('A101', '$'), ('A103', '£'), ('B101', '@'), ('C101', '€')]

通过解压缩,可以很容易地将其概括为两个以上的列表.

This can easily be generalized to more than two lists with unpacking.

list = ['A103', 'A101', 'B101']
rad = ['£', '$', '@']
more = [1, 2, 3]

lists = list, rad, more

...

list_sorted = sorted(zip(*lists), key=alphanum_key)

print(list_sorted) # [('A101', '$', 2), ('A103', '£', 1), ('B101', '@', 3)]

这篇关于根据另一个列表的排序方式对列表进行排序.的Python 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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