我有一个问题是在动态元组列表中获得最高值.
List可能如下所示:
adymlist = [[('name1',1)],[('name2',2),('name3',1), ...('name10', 20)], ...,[('name m',int),..]]
现在我遍历List以获得最高值(整数):
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>所以我尝试用max(a,key = int)扩展max函数,但是我得到了一个Type Error.
希望你能理解我想要的东西;-)
UPDATE
谢谢到目前为止.
如果我使用itertools.chain(* adymlist)和max(flatlist,key = lambda x:x [1])
我会得到一个例外:max_word = max(flatlist,key = lambda x:x [1])
TypeError:’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]
它仍然做我想要的,但它不是脏吗?