python 中求最大值问题_python – 元组列表中的最大值

我有一个问题是在动态元组列表中获得最高值.

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]

它仍然做我想要的,但它不是脏吗?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值