我在获取元组列表的动态列表中的最高值时遇到问题。
列表可以如下所示:
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 but z > a 所以我尝试用 max(a, key=int)
扩展 max 函数,但我得到了类型错误。
希望你能明白我想要什么;-)
更新
到目前为止谢谢。如果我使用 itertools.chain(*adymlist)
和 max(flatlist, key=lambda x: x[1])
我会得到一个异常:max_word = max(flatlist, key=lambda x: x[1])
TypeError: 'int' 对象不可订阅
但是如果我使用 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]
它仍然可以满足我的要求,但不是太脏了吗?
最佳答案
澄清一下,看起来您有一个元组列表列表。看起来我们并不关心它们在什么列表中,所以我们可以将其简化为两个步骤
- 将列表列表展平为元组列表
- 找到最大值
第一部分可以通过 itertools.chain
完成(参见例如 Flattening a shallow list in Python)
第二个可以通过max来解决,你的想法是对的,但是你应该传入一个函数而不是你想要的类型。此函数需要返回您键入的值,在本例中为元组的第二部分
max(flatlist, key=lambda x: x[1])
更正
我重新阅读了您的问题 - 您是在寻找每个子列表中的最大值吗?如果是这种情况,则只有第二部分适用。只需为每个列表遍历您的列表
比你现在想要的更 pythonic
output = []
for lst in lists:
output.append( max(flatlist, key=lambda x: x[1]) )
或
map(lambda x: max(x, key=lambda y: y[1]) , lists)
关于python - 元组列表列表中的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4963957/