![](/img/trans.png)
[英]How do I find the minimum/maximum value for each key in a dictionary? And how do I find the number of values for each key?
[英]how do I find the maximum number of values of an array?
说我有这个数组:
Letters = ["A","B","C","D"]
#A #B #C #D
numbers = [ [1,4,3],[2,4,5,5],[3],[2,3] ]
我想找到这些数组中最长的一个,并想要这样的输出:
B has the most values
我尝试过这样的事情
Letters = ["A","B","C","D"]
#A #B #C #D
numbers = [ [1,4,3],[2,4,5,5],[3],[2,3] ]
length = 0
maximum = 0
for i in numbers:
for x in i:
lenght = len(numbers)
if length > maximum:
maximum = length
print(maximum)
您可以同时zip
两个列表,并使用max
内置函数和自定义key
来查找列表最长的元组:
from operator import itemgetter
s = max(zip(Letters, numbers), key= lambda x: len(itemgetter(1)(x)))[0]
输出量
print(s, 'has the most values')
# B has the most values
由于只需要列表的长度及其位置,因此将numbers
转换为长度列表,其中每个长度的位置对应于每个子列表的位置:
numbers_lengths = list(map(len, numbers)) # using `list` is not necessary # numbers_lengths == [3, 4, 1, 2]
您想要将letters
每个元素与长度相关联,这意味着您需要一个不同的数据结构:
Map = dict(zip(letters, numbers_lengths)) # Map == {'A': 3, 'B': 4, 'C': 1, 'D': 2}
只需找到价值最大的密钥即可:
result = max([(length, letter) for letter, length in Map.items()]) # result == (4, 'B')
之所以有效,是因为您可以比较元组: ((2, 'a') > (0, 'b')) is True
。
3.1另一种方法:
result = max(Map.items(), key=lambda pair: pair[1]) # result == ('B', 4)
因此,答案是result[1] == 'B'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.