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

问题描述 投票:0回答:1

我正在努力理解返回正在做什么以及-1的重要性是什么,因为更改它不会返回列表中最不常见的值。

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])
python python-3.x
1个回答
3
投票

Python列表的一个简洁功能是您可以从列表的末尾开始索引。您可以通过将负数传递给[]来完成此操作。它基本上将len(array)视为第0个指数。所以,如果你想要array中的最后一个元素,你可以调用array[-1]

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

temp = c.most_common()
return temp[len(temp) - 1]
© www.soinside.com 2019 - 2024. All rights reserved.