![](/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.