trolle3000
trolle3000

Reputation: 1067

Python: extract tuples with max/min n'th element from array of tuples

In Python I have some data that looks like this:

A = [
(-9, [(2, 3), (5, 2), (3,1)]), 
(-8, [(3, 4), (5, 6), (7, 6)]), 
(-8, [(0, 0), (5, 0), (1, 6)]),
(-9, [(2, 3), (4, 2), (4, 5)]), 
]

What is the most pythonic way to extract the element or elements that have the maximum value in the first entry? Changing the data structure is not an option.

In this example, the goal is to return the two middle tuples.

Cheers!

Upvotes: 2

Views: 2472

Answers (1)

Mark Byers
Mark Byers

Reputation: 838696

Try a list comprehension:

max_value = max(x[0] for x in A)
print [x for x in A if x[0] == max_value]

See it working online: ideone

Upvotes: 8

Related Questions