我有一個問題,在元組列表的動態列表中獲得最高值。
的可列表如下:元組列表中的最大值
adymlist = [[('name1',1)],[('name2',2),('name3',1), ...('name10', 20)], ...,[('name m',int),..]]
現在我遍歷列表,以獲得最高值(整數):
total = {}
y=0
while y < len(adymlist):
if len(adymlist) == 1:
#has the List only 1 Element -> save it in total
total[adymlist[y][0][0]] = adymlist[y][0][1]
y += 1
else:
# here is the problem
# iterate through each lists to get the highest Value
# and you dont know how long this list can be
# safe the highest Value in total f.e. total = {'name1':1,'name10':20, ..}
我嘗試了很多,以獲得最大的價值,但我發現對我的問題沒有結論。我知道我必須遍歷列表中的每個元組,並將其與下一個元組進行比較,但它不知道如何對它進行正確編碼。
另外我可以使用函數max()
,但它不適用於字符串和整數。 F.E. a = [ ('a',5),('z',1)]
- >結果是max(a) ---> ('z',1)
obv 5> 1但z> a所以我試圖擴大與max(a, key=int)
最大功能,但我得到一個類型錯誤。
希望你能明白我想;-)
UPDATE
感謝這麼遠。如果我使用itertools.chain(*adymlist)
和max(flatlist, key=lambda x: x[1])
我會得到這樣的異常:max_word = MAX(flatlist,鍵=拉姆達X:X [1]) 類型錯誤: 'INT' 目的是unsubscriptable
但是,如果我使用itertools.chain(adymlist)
它工作正常。但是我不知道如何總結列表中的每個元組的所有整數。我需要你的幫助來弄明白。
否則,我爲itertools.chain(*adymlist)
寫了一個解決方法,以獲得該列表中所有整數和最高整數的總和。
chain = itertools.chain(*adymlist)
flatlist = list(chain)
# flatlist = string, integer, string, integer, ...
max_count = max(flatlist[1:len(flatlist):2])
total_count = sum(flatlist[1:len(flatlist):2])
# index of highest integer
idx = flatlist.index(next((n for n in flatlist if n == max_count)))
max_keyword = flatlist[idx-1]
它仍然做我想要的東西,但它不是骯髒?