[英]“What does this mean: key=lambda x: x[-1] ?”
I know that a.sort(key=lambda x: x[1])
means it sorts with respect to second element. 我知道
a.sort(key=lambda x: x[1])
表示它相对于第二个元素进行排序。
But x[-1]
?? 但是
x[-1]
??
Shouldn't there be only two configurations x[0]
and x[1]
? 不应该只有两个配置
x[0]
和x[1]
吗?
Or am I missing something obvious? 还是我缺少明显的东西?
Lets consider a = [(10, 4), (3, 5), (7, 1)]
让我们考虑
a = [(10, 4), (3, 5), (7, 1)]
Python has the ability to index from the end
of a list. Python可以从列表的
end
开始索引。 Hence, x[-1]
refers to the last element, x[-2]
refers to the second to last element, etc. 因此,
x[-1]
表示最后一个元素, x[-2]
表示倒数第二个元素,依此类推。
a.sort(key=lambda x: x[-1])
will sort a
by the last element. 将整理
a
由最后一个元素。
>>> a = [(10, 4), (3, 5), (7, 1)]
>>> a.sort(key=lambda x: x[-1])
[(7, 1), (10, 4), (3, 5)]
您正在按每个元组的最后一个元素进行排序(即,分别按4、5、1而不是10、3、7进行排序)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.