Reputation: 21019
I have a list of tuples, which may look like this:
[(23, 'somestr'), (30, 'someotherstr'), (15, 'someotherstr2')]
I need to extract the tuple which has the minimum number, and get the string of that tuple. To find the minimum, I just did: min([i[0] for i in list])
.
How would get the string though? A nested list comprehension? I've tried several ways but I',m not sure how to either retain the tuple's index, or get it within the list comprehension statement.
Upvotes: 0
Views: 287
Reputation: 428
python 3.2
1. min(your_list)
2. sorted(your_list)[0]
3. min([(i,v) for i,v in your_list])
Upvotes: -1
Reputation: 500397
Here, you can just compare the tuples directly. However, a more general approach is to use the key
argument to min()
:
In [21]: min(l, key=operator.itemgetter(0))[1]
Out[21]: 'someotherstr2'
Here, key=operator.itemgetter(0)
extracts the zeroth element of the tuple and uses the result as the key to decide which tuple is the smallest.
Upvotes: 3
Reputation: 375604
Tuples can be compared:
>>> (1, 'hello') < (2, 'bye')
True
Tuples are compared kind of like strings: consider elements pairwise until you find an unequal pair, and then the tuple with the smaller element is considered smaller.
So you can simply get the minimum of the list, and the tuple with the lowest first value will be returned. Then you can look at the string in the second element:
least = min(the_list)
print least[1]
Upvotes: 2