假设我有3种维生素,含有C-维生素和D-维生素
ls = [[100,50],[100,49],[100,64]]
巧合的是,这些维生素都含有相同量的维生素C。因此,我想对第二种情况(维生素D)进行分类。我要怎样才能做到呢?我做了一些研究,发现这是一个例子:
^{pr2}$
但是我不明白它是怎么工作的,为什么会这样。我已经使用一个带有helpmethods的类和以下行实现了对一个条件的列表排序:
ls.sort(key=Vitamin.get_cVitamin, reverse=True)
我更希望以此为基础。。在
Tags:
默认情况下,标准排序将考虑所包含列表的其他列。在
因此,只使用不带任何键的普通排序函数。在
还可以看看documentation[emphasis mine]:
但是,如果需要选择特定的列来定义排序顺序,我建议使用^{} 作为
key
函数。在要按第一个元素排序,请按第二个元素断开连接,请使用以下命令:
^{pr2}$在lambda中使用的任何要排序的元素,即第二、第三个元素都是
(x[1],x[2])
。在如果你只处理数字,你可以排序:
如果子列表的一个值在列表的所有子列表中都相同,
sorted()
方法默认按其他值排序,即不同的值。您不需要使用lambda
。在演示:
按多个键排序:
^{pr2}$在这里,列表首先按第二个索引排序,即第1个键,如果索引2上的值相等,则索引3(即第2个键用于在这些情况下进行排序。在
相关问题 更多 >
编程相关推荐