我正在努力理解返回正在做什么以及-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列表的一个简洁功能是您可以从列表的末尾开始索引。您可以通过将负数传递给[]
来完成此操作。它基本上将len(array)
视为第0个指数。所以,如果你想要array
中的最后一个元素,你可以调用array[-1]
。
您所有的return c.most_common()[-1]
语句都是调用c.most_common
并返回结果列表中的最后一个值,这将为您提供该列表中最不常见的项目。基本上,这一行相当于:
temp = c.most_common()
return temp[len(temp) - 1]