[英]how do I find the maximum number of values of an array?
Say I have this array: 说我有这个数组:
Letters = ["A","B","C","D"]
#A #B #C #D
numbers = [ [1,4,3],[2,4,5,5],[3],[2,3] ]
I would like to find which of these arrays is the longest and want an output like this: 我想找到这些数组中最长的一个,并想要这样的输出:
B has the most values
I attempted something like this 我尝试过这样的事情
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)
You could zip
both lists and use the max
built-in function with a custom key
to find the tuple with the longest list: 您可以同时
zip
两个列表,并使用max
内置函数和自定义key
来查找列表最长的元组:
from operator import itemgetter
s = max(zip(Letters, numbers), key= lambda x: len(itemgetter(1)(x)))[0]
Output
输出量
print(s, 'has the most values')
# B has the most values
Since you only need the lists' lengths and their positions, convert numbers
to a list of lengths, where the positions of each length correspond to the positions of each sublist: 由于只需要列表的长度及其位置,因此将
numbers
转换为长度列表,其中每个长度的位置对应于每个子列表的位置:
numbers_lengths = list(map(len, numbers)) # using `list` is not necessary # numbers_lengths == [3, 4, 1, 2]
You want to associate each element of letters
with a length, which means you need a different data structure: 您想要将
letters
每个元素与长度相关联,这意味着您需要一个不同的数据结构:
Map = dict(zip(letters, numbers_lengths)) # Map == {'A': 3, 'B': 4, 'C': 1, 'D': 2}
Just find the key whose value is the greatest: 只需找到价值最大的密钥即可:
result = max([(length, letter) for letter, length in Map.items()]) # result == (4, 'B')
This works because you can compare tuples: ((2, 'a') > (0, 'b')) is True
. 之所以有效,是因为您可以比较元组:
((2, 'a') > (0, 'b')) is True
。
3.1 Another approach: 3.1另一种方法:
result = max(Map.items(), key=lambda pair: pair[1]) # result == ('B', 4)
So, the answer is result[1] == 'B'
因此,答案是
result[1] == 'B'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.