-1

I want to extract from a list of tuples (int, string) the string value of the tuple with minimum int.

For example, if I have this list:

l = [('a', 5), ('b', 3), ('c', 1), ('d', 6)]

The output should be 'c', because the minimum integer is in the tuple ('c', 1).

I've tried different things, none worked so far. Thanks.

ArianJM
  • 676
  • 12
  • 25
  • 3
    `I've tried different things, none worked so far.` post an attempt from that. – Avinash Raj Jan 09 '15 at 13:08
  • Well, I've tried the answer found here: https://stackoverflow.com/questions/17468923/how-to-find-a-min-value-of-a-row-in-a-specified-column-in-a-tuple-python-2-6 but couldn't understand what was happening and adapt it to my case, and also, tried with the `zip` and `map` functions as shown here: https://stackoverflow.com/questions/4002796/python-find-the-min-max-value-in-a-list-of-tuples – ArianJM Jan 09 '15 at 13:15
  • Try this l = [('a', 5), ('b', 3), ('c', 1), ('d', 6)] p=[min(l[i]) for i in range(len(l))] l[p.index(min(p))] using list index and – Anandhakumar R Jan 09 '15 at 13:17
  • Alternatively, you could use a dictionary since you list of tuple looks a lot like it: `d = dict(l)` then `min(d, key=d.get)`. – Vincent Jan 09 '15 at 13:22

2 Answers2

1

Try using the min() function with a key lambda:

min_tuple = min(l, key=lambda x:x[1])

This makes use of the min function which returns the minimum element on an iterable. An inline lambda function is used, which is a kind of comparator of tuple elements, so I'm returning as the key the second item of the tuple (the int). So when the min function is executed using this key function the minimum tuple is the one containing the minimum integer.

avenet
  • 2,894
  • 1
  • 19
  • 26
0

You could use min() for this:

In [1]: l = [('a', 5), ('b', 3), ('c', 1), ('d', 6)]

In [2]: min(l, key=lambda t:t[1])
Out[2]: ('c', 1)
NPE
  • 486,780
  • 108
  • 951
  • 1,012