根据特定列对列表列表进行排序

2024-09-28 16:22:04 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有3种维生素,含有C-维生素和D-维生素

ls = [[100,50],[100,49],[100,64]]

巧合的是,这些维生素都含有相同量的维生素C。因此,我想对第二种情况(维生素D)进行分类。我要怎样才能做到呢?我做了一些研究,发现这是一个例子:

^{pr2}$

但是我不明白它是怎么工作的,为什么会这样。我已经使用一个带有helpmethods的类和以下行实现了对一个条件的列表排序:

ls.sort(key=Vitamin.get_cVitamin, reverse=True)

我更希望以此为基础。。在


Tags: key列表get排序分类情况条件sort
3条回答

默认情况下,标准排序将考虑所包含列表的其他列。在

因此,只使用不带任何键的普通排序函数。在

ls = [[100,50],[100,49],[100,64]]
ls.sort()
# ls is sorted w.r.t. all "columns": [[100, 49], [100, 50], [100, 64]]

还可以看看documentation[emphasis mine]:

Sequence types also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length. (For full details see Comparisons in the language reference.)

但是,如果需要选择特定的列来定义排序顺序,我建议使用^{}作为key函数。在

ls.sort(key=lambda x: x[1],reverse=True)
print(ls)

[[100, 64], [100, 50], [100, 49]]

要按第一个元素排序,请按第二个元素断开连接,请使用以下命令:

^{pr2}$

在lambda中使用的任何要排序的元素,即第二、第三个元素都是(x[1],x[2])。在

如果你只处理数字,你可以排序:

ls = [[100,50],[100,49],[100,64]]
ls.sort(reverse=True)

如果子列表的一个值在列表的所有子列表中都相同,sorted()方法默认按其他值排序,即不同的值。您不需要使用lambda。在

演示:

>>> ls = [[100,50],[100,49],[100,64]]
>>> sorted(ls)
[[100, 49], [100, 50], [100, 64]]
>>> ls = [[50,100],[49,100],[64,100]]
>>> sorted(ls)
[[49, 100], [50, 100], [64, 100]]

按多个键排序:

^{pr2}$

在这里,列表首先按第二个索引排序,即第1个键,如果索引2上的值相等,则索引3(即第2个键用于在这些情况下进行排序。在

相关问题 更多 >