Reputation: 77
I'm trying to obtain the nth elements from a list of tuples in python equal to a certain value
I have a much larger list of something like this
num = [('A15', 2, 'BC', 721.16), ('A21', 3, 'AB', 631.31), ('A42', 4, 'EE', 245.43)]
I wish to extract only the tuples with the 2nd element of the tuple equal to a given value i.e. 2 in this example and from those find the largest 4th element
Currently my code looks like the following
for ((x[1] for x in num) = 1):
num_max = max(num_list,key=lambda item:item[3])
the problem's something to do with setting the list comprehension equal to a value as that's what's giving me a syntax error
Apologies if this has already been answered but I couldn't find it
Upvotes: 2
Views: 127
Reputation: 16091
Try like this,
In [1]: num = [('A15', 2, 'BC', 721.16), ('A21', 3, 'AB', 631.31),
('A42', 4, 'EE', 245.43),('A15', 2, 'BC', 856.16)]
In [2]: max((i for i in num if i[1] == 2),key=lambda x:x[3])
Out[2]: ('A15', 2, 'BC', 856.16)
Upvotes: 1
Reputation: 42746
You have several options, using filter
and max
for example:
result = max(filter(lambda x: x[1] == 2, num_list), key=lambda x: x[3])
As commented by @chrisz, but instead of a list
use a generator
:
result = max((i for i in x if i[1] == 2), key=lambda x: x[3])
Note: If using python2
consider using itertools.ifilter
instead of filter
to avoid extra memory.
Upvotes: 0