我有一个问题,在元组列表的动态列表中获得最高值。
的可列表如下:元组列表中的最大值
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]
它仍然做我想要的东西,但它不是肮脏?