Python的 - 找到最接近的整数为0列表 [英] Python - find integer closest to 0 in list

查看:1132
本文介绍了Python的 - 找到最接近的整数为0列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  <一href="http://stackoverflow.com/questions/9706041/finding-index-of-an-item-closest-to-the-value-in-a-list-thats-not-entirely-sort">finding最近的一个项目中,这不是完全排序

我有在Python(正负号的列表 [237,72,-18,237,236,237,60,-158,-273,-78,492, 243] )。我想找到最接近0的数字如何做到这一点?

I've got a list of positive and negative numbers in Python ([237, 72, -18, 237, 236, 237, 60, -158, -273, -78, 492, 243]). I want to find the number which is closest to 0. How do I do this?

推荐答案

这个怎么样:

lst = [237, 72, -18, 237, 236, 237, 60, -158, -273, -78, 492, 243]
min((abs(x), x) for x in lst)[1]

正如已经指出的意见,这是一个很好的和更短的回答:

As has been pointed in the comments, this is a nice and much shorter answer:

min(lst, key=abs)

这篇关于Python的 - 找到最接近的整数为0列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆