2

I have this list of list of tuples

var1 = [
    [(10, '♣'), (7, '♠')],
    [(14, '♣'), (2, '♣')],
    [(2, '♥'), (9, '♦')],
    [(11, '♠'), (10, '♠')],
    [(11, '♦'), (5, '♣')]
]

and I wanna extract the tuple with the maximun value which is the second one or var1[1]. I've used a lot of different codes during my programming but the one I'm using now and until now and didn't have any major issues is this one:

 maximo = max(var1, key=lambda x: sum(i for i,_ in x))

also this one:

 maximo2 = list(map(max,zip(*var1)))

The problem is I need the list with the biggest value, not the one with the combinations of the 2 biggest, and right now this code is outputting var1[3] as the bigger of the 2 and I don't know what else to try.

colidyre
  • 4,170
  • 12
  • 37
  • 53

3 Answers3

5

Use max instead of sum

Ex:

var1=[[(10, '♣'), (7, '♠')], [(14, '♣'), (2, '♣')], [(2, '♥'), (9, '♦')], [(11, '♠'), (10, '♠')], [(11, '♦'), (5, '♣')]]
maximo=max(var1, key=lambda x: max(i for i,_ in x))
print(maximo)

Output:

[(14, '♣'), (2, '♣')]
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1

you can use the built-in function max with parameter key:

max(var1, key=max)

output:

[(14, '♣'), (2, '♣')]
kederrac
  • 16,819
  • 6
  • 32
  • 55
0

You could use max and operator.itemgetter here as well:

>>> from operator import itemgetter
>>> var1=[[(10, '♣'), (7, '♠')], [(14, '♣'), (2, '♣')], [(2, '♥'), (9, '♦')], [(11, '♠'), (10, '♠')], [(11, '♦'), (5, '♣')]]
>>> max(var1, key=itemgetter(0))
[(14, '♣'), (2, '♣')]
RoadRunner
  • 25,803
  • 6
  • 42
  • 75