[英]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 我想找到位于位置
[1]
最接近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? 但是,当我尝试将字符串转换为浮点型时,会引发异常; /如何实际执行此操作?
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. min
函数将基于key
函数比较列表中的每个元素。
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.