简体   繁体   English

获取元组列表中的最大值

[英]Get the max value on a list of tuples

I have a list of tuples:我有一个元组列表:

card_list= [(2, (1, S)), (0, (12, H)), (1, (5, C)]

This list contains cards: (cardindex, (value, suit)) where cardindex is a index to store the position of the card but irrelevant for this my particular question.此列表包含卡片:(cardindex, (value,suit)) 其中 cardindex 是存储卡片位置的索引,但与我的特定问题无关。

So in the example there are 3 cards in the list:因此,在示例中,列表中有 3 张卡片:

  • (2, (1, S)) = Ace of Spades with an index of 2. (2, (1, S)) = 指数为 2 的黑桃 A。
  • (0, (12, H)) = King of Hearts with an index of 0 (0, (12, H)) = 指数为 0 的红心之王
  • (1, (5, C)) = 5 of Clubs with index 1 (1, (5, C)) = 5 个指数为 1 的俱乐部

Well, my question is: I desire to obtain the item with the max value, this is, i have to get the item: (0, (12, H))好吧,我的问题是:我希望获得具有最大值的项目,这是,我必须获得该项目:(0, (12, H))

My attempt is:我的尝试是:

CardWithHighestValue= max(card_list,key=itemgetter(1)[0])

But I get the item or the value?但我得到了物品或价值? And the most important: is it really correct that sentence?最重要的是:那句话真的正确吗?

Thanks in advance.提前致谢。

replace代替

CardWithHighestValue= max(card_list,key=itemgetter(1)[0])

with

CardWithHighestValue= max(card_list,key=itemgetter(1))

Demo演示

from operator import itemgetter
card_list= [(2, (1, "S")), (0, (12, "H")), (1, (5, "C"))]
print max(card_list,key=itemgetter(1)) 

card_list= [(2, (1, "S")), (0, (4, "H")), (1, (5, "C"))]
print max(card_list,key=itemgetter(1))

Output:输出:

(0, (12, 'H'))
(1, (5, 'C'))

You can also use an anonymous function as key:您还可以使用匿名函数作为键:

Demo:演示:

print(max(card_list, key=lambda x:x[1]))

Output:输出:

(0, (12, 'H'))

Try this:尝试这个:

lst=[(1,('a',10)), (2,('b',10)),(10,('a',10)), (3,('a',10))]

So所以

print("min: ", min(lst)[0]) # min: 1

And

print("max: ", max(lst)[0]) # max:  10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM