numbers = {'a': 1, 'b': 4, 'c': 1, 'd':4 , 'e': 3}
mx_tuple = max(numbers.items(),key = lambda x:x[1]) #max function will return a (key,value) tuple of the maximum value from the dictionary
max_list =[i[0] for i in numbers.items() if i[1]==mx_tuple[1]] #my_tuple[1] indicates maximum dictionary items value
print(max_list)
印刷品
它的作用是,通过
.iteritems
循环所有条目,然后检查该值是否为最大值,如果是,则将键添加到列表中。collections.Counter
对象对此也很有用。它为您提供了一个.most_common()
方法,该方法将为您提供所有可用值的键和计数:此代码将在O(n)中工作。在求最大值时为O(n),在列表理解中为O(n)。所以总的来说还是O(n)。
注:O(2n)等于O(n)。
相关问题 更多 >
编程相关推荐