1

I have a list of tuples:

lst = [('54', '1.74', '253.2'), ('342', '2.85', '13.46'), ('53','2.43', '15.63')]

I want to find the tuple with item at position [1] closest to 2.0

I go like this:

number = lst[0][1]
for i in lst:
    if abs(float(i[1]) - 2) < float(number):
        number = i[1]
        if number in i:
            print i

But when I'm trying to convert the string to float it raises an exception ;/ How can I actually do this?

nutship
  • 4,624
  • 13
  • 47
  • 64

1 Answers1

7

This should do the trick ...

min(lst,key=lambda x: abs(float(x[0]) - 2))

The min function will compare each element in the list based on the key function.

demo:

>>> lst = [('1.74', '253.2'), ('2.85', '13.46'), ('2.43', '15.63')]
>>> min(lst,key=lambda x: abs(float(x[0]) - 2))
('1.74', '253.2')
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • Thank you very much for this reply. Something is however not working for me ;/. I'm scraping a website and my code looks like this: `lst = re.findall(pattern, html)` which produces a list of 3-item tuples `[('54', '1.74', '253.2'), ('342', '2.85', '13.46'), ('53','2.43', '15.63')]` going on `lst = min(lst,key=lambda x: abs(float(x[1] - 2))` and `print lst` I'm getting an `Invalid syntax` error. You know what's up here? – nutship Mar 13 '13 at 21:10
  • 1
    you've misplaced a paren. You need: `abs(float(x[1])-2)` instead of `abs(float(x[1] - 2))`. – Maus Mar 13 '13 at 21:31
  • Thank you sooo much @Maus. You don't even know how much this got on my nerves lol :) – nutship Mar 13 '13 at 21:53
  • 1
    +1 for this very clean (and fast running) answer. FWIW, this same approach can be used with *heapq.nsmallest()* to find the *n* closest values and with *sorted()* to rank order all of the inputs by their nearness to the target value. – Raymond Hettinger Jun 09 '14 at 01:32
  • @RaymondHettinger -- Thanks for the +1. Coming from you it means a great deal :-). And the `heapq` and `sorted` notes are good points. It's beautiful how consistent the core language and the standard lib are in a number of places. – mgilson Jun 09 '14 at 05:13