列表的自定义排序顺序

列表的自定义排序顺序

本文介绍了列表的自定义排序顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下列表:

mylist1 = ['alpha', 'green']
mylist2 = ['blue', 'alpha', 'red']

我想通过此自定义排序列表对这两个列表进行排序:['red','blue','green','alpha']

I want to sort these two lists by this custom ordered list: ['red','blue','green','alpha']

这样mylist1 = ['green', 'alpha']mylist2 = ['red','blue','alpha']

如何在Python中执行此操作?

How can i do this in Python?

推荐答案

演示:

>>> mylist1 = ['alpha', 'green']
>>> mylist2 = ['blue', 'alpha', 'red']
>>> sort_order = ['red', 'blue', 'green', 'alpha']
>>> mylist1.sort(key=sort_order.index)
>>> mylist1
['green', 'alpha']
>>> mylist2.sort(key=sort_order.index)
>>> mylist2
['red', 'blue', 'alpha']

说明:

list.sort中的key参数使列表通过比较key(element)而不是element来确定顺序.例如,要进行不区分大小写的排序,您可以传递key函数,该函数使字符串变为小写.比较了小写元素,但保留了原始元素:

The key parameter in list.sort causes the list to determine the order by comparing key(element) instead of element. For example, to do case-insensitive sort, you can pass a key function which makes the string lowercase. The lowercase elements are compared, but the original elements are preserved:

>>> x = ["age", "Bonkers", "cheese"]
>>> x.sort()
>>> x
['Bonkers', 'age', 'cheese']
>>> str.lower("Bonkers")
'bonkers'
>>> x.sort(key=str.lower)
>>> x
['age', 'Bonkers', 'cheese']

使用sort_order.index作为键使用元素在sort_order列表中具有的索引来确定顺序,而不是元素本身.因此,'red'使用0'blue'使用1,依此类推...结果是要排序的列表根据每个元素在sort_order中的位置进行了排序.

Using sort_order.index for the key uses the index that element has in the sort_order list to determine the order instead of the element itself. So 'red' uses 0, 'blue' uses 1, etc... the result is that the list to be sorted gets sorted according to where each element is in sort_order.

这篇关于列表的自定义排序顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 10:22