gpt4 book ai didi

python - Python 中 list[-1] 的含义

转载 作者:行者123 更新时间:2023-12-04 14:30:51 26 4
gpt4 key购买 nike

我在这里有一段代码,它应该返回元素列表中最不常见的元素,按共性排序:

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])
我的问题在于 return c.most_common()[-1] 中 -1 的重要性.将此值更改为任何其他值会破坏代码,因为不再返回最不常见的元素。那么,-1 在这种情况下意味着什么?

最佳答案

Python 列表的一项巧妙功能是您可以从列表的末尾开始索引。您可以通过将负数传递给 [] 来做到这一点。 .它本质上是治疗 len(array)作为第 0 个索引。所以,如果你想要 array 中的最后一个元素,您会拨打 array[-1] .

您所有的 return c.most_common()[-1]声明确实是调用 c.most_common并返回结果列表中的最后一个值,这将为您提供该列表中最不常见的项目。本质上,这一行相当于:

temp = c.most_common()
return temp[len(temp) - 1]

关于python - Python 中 list[-1] 的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52395099/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com