用两个键对Python列表进行排序,但只有一个以相反的顺序 [英] sort Python list with two keys but only one in reverse order
问题描述
我想知道用Python方式通过两个键对元组列表进行排序的方式,从而用一个(只有一个)键的排序是相反的,而用另一个键进行排序将是不区分大小写的. 更具体地说,我有一个包含如下元组的列表:
I was wondering what would be a Pythonic way of sorting a list of tuples by two keys whereby sorting with one (and only one) key would be in a reverse order and sorting with the the other would be case insensitive. More specifically, I have a list containing tuples like:
myList = [(ele1A, ele2A),(ele1B, ele2B),(ele1C, ele2C)]
我可以使用以下代码通过两个键对其进行排序:
I can use the following code to sort it with two keys:
sortedList = sorted(myList, key = lambda y: (y[0].lower(), y[1]))
要以相反的顺序排序,我可以使用
To sort in reverse order I can use
sortedList = sorted(myList, key = lambda y: (y[0].lower(), y[1]), reverse = True)
,但这将使用两个键以相反的顺序排序.
but this would sort in a reverse order with two keys.
任何提示都将不胜感激.
Any hints greatly appreciated.
推荐答案
当我们需要对具有两个约束的列表进行排序时,将使用两个键,一个约束以升序排列,另一个约束以降序排列在同一列表或任何其他列表中
在您的示例中,
sortedList = sorted(myList, key = lambda y: (y[0].lower(), y[1]))
只能以一种顺序对整个列表进行排序
您可以尝试这些并检查发生了什么
Two keys will be used when we need to sort a list with two constraints one in ascending order and other in descending in the same list or any
In your example sortedList = sorted(myList, key = lambda y: (y[0].lower(), y[1]))
can sort entire list only in one order
you can try these and check whats happening
sortedList = sorted(myList, key = lambda y: (y[0].lower(), -y[1]))
sortedList = sorted(myList, key = lambda y: (-y[0].lower(), y[1]))
sortedList = sorted(myList, key = lambda y: (-y[0].lower(), -y[1]))
希望您以后会明白;)
这篇关于用两个键对Python列表进行排序,但只有一个以相反的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!