我想在yrs
中找到最接近2013(_tmp
)的元素。
yrs = [2000.0, 2001.0, 2002.0, 2003.0, 2004.0, 2005.0, 2006.0, 2007.0, 2008.0, 2009.0, 2010.0, 2011.0, 2012.0, 2014.0, 2015.0, 2016.0]
_tmp = 2013
min(yrs, key=lambda x: abs(x - _tmp))
我尝试过列表理解,但它会抛出NameError
。我怎么能这样做?也许是numpy?
答案 0 :(得分:1)
正如我所提到的,使用np.argmin
:
yrs[np.abs(np.array(yrs) - _tmp).argmin()]
yrs
转换为numpy.ndarray
(如果已经是数组则跳过)_tmp
yrs
np.abs
找到绝对值(我们希望绝对最少)np.argmin
找到最小值的索引yrs
以完成工作。答案 1 :(得分:0)
找到与数字最接近的值的另一种方法
yrs = [2000.0, 2001.0, 2002.0, 2003.0, 2004.0, 2005.0, 2006.0, 2007.0, 2008.0, 2009.0, 2010.0, 2011.0, 2012.0, 2014.0, 2015.0, 2016.0]
yr = 2013
# creates a list l, with the difference between input year and items in yrs
# find the element having the minimum difference with the input element (yr)
l = [abs(x-yr) for x in yrs]
if l:
print(int(yrs[l.index(min(l))]))
>>> 2012