Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

python - 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.

So in the example there are 3 cards in the list:

  • (2, (1, S)) = Ace of Spades with an index of 2.
  • (0, (12, H)) = King of Hearts with an index of 0
  • (1, (5, C)) = 5 of Clubs with index 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))

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...