使用两个键对 Python 列表进行排序,但只有一个键以相反的顺序排列

2023-09-01Python开发问题
1

本文介绍了使用两个键对 Python 列表进行排序,但只有一个键以相反的顺序排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想知道通过两个键对元组列表进行排序的 Pythonic 方法是什么,其中使用一个(并且只有一个)键进行排序将是相反的顺序,而使用另一个键进行排序将不区分大小写.更具体地说,我有一个包含元组的列表,例如:

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]))

我可以使用倒序排序

sortedList = sorted(myList, key = lambda y: (y[0].lower(), y[1]), reverse = True)

但这将使用两个键以相反的顺序排序.

but this would sort in a reverse order with two keys.

推荐答案

当我们需要对具有两个约束的列表进行排序时,将使用两个键,一个按升序排列,另一个按降序排列在同一个列表中或任何
在您的示例中
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]))

希望你在这之后会明白;)

hope you will understand after this ;)

这篇关于使用两个键对 Python 列表进行排序,但只有一个键以相反的顺序排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10