nutship
nutship

Reputation: 4924

Finding number closest to cerain value

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?

Upvotes: 1

Views: 2011

Answers (1)

mgilson
mgilson

Reputation: 309831

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')

Upvotes: 7

Related Questions