[英]Meaning of list[-1] in Python
I have a piece of code here that is supposed to return the least common element in a list of elements, ordered by commonality:我这里有一段代码应该返回元素列表中最不常见的元素,按共性排序:
def getSingle(arr):
from collections import Counter
c = Counter(arr)
return c.most_common()[-1] # return the least common one -> (key,amounts) tuple
arr1 = [5, 3, 4, 3, 5, 5, 3]
counter = getSingle(arr1)
print (counter[0])
My question is in the significance of the -1 in return c.most_common()[-1]
.我的问题是 -1 的意义在于return c.most_common()[-1]
。 Changing this value to any other breaks the code as the least common element is no longer returned.将此值更改为任何其他值都会破坏代码,因为不再返回最不常见的元素。 So, what does the -1 mean in this context?那么,-1 在这种情况下意味着什么?
One of the neat features of Python lists is that you can index from the end of the list. Python 列表的简洁功能之一是您可以从列表的末尾开始索引。 You can do this by passing a negative number to []
.您可以通过将负数传递给[]
来做到这一点。 It essentially treats len(array)
as the 0th index.它本质上将len(array)
视为第 0 个索引。 So, if you wanted the last element in array
, you would call array[-1]
.所以,如果你想要array
中的最后一个元素,你可以调用array[-1]
。
All your return c.most_common()[-1]
statement does is call c.most_common
and return the last value in the resulting list, which would give you the least common item in that list.您的所有return c.most_common()[-1]
语句所做的就是调用c.most_common
并返回结果列表中的最后一个值,这将为您提供该列表中最不常见的项目。 Essentially, this line is equivalent to:本质上,这一行相当于:
temp = c.most_common()
return temp[len(temp) - 1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.