查找最接近零的数字索引(列表)

Finding indices of numbers closest to zero (list)

我有一个数字列表,当我绘制它们时,我得到了这个 top-hat 类型的函数。 FWHM 在 y 轴上出现在零处。因此,如果我找出绘图为零的 x 值(在两个地方),差异将给我 FWHM。

但是,列表中的每个数字都是浮点数,所以我必须找到最接近零的数字。 CAX_roots 是绘制的列表。我可以使用以下代码找到第一个:

root =  min(abs(x) for x in CAX_roots)
first_root = str(CAX_roots).find(str(root))
print first_root

关于如何找到第二个根的任何 help/advice?当我尝试从 first_root 值继续迭代到列表末尾时,我似乎无法克服错误 "list indices must be integers, not tuple":

CAX_roots2 = CAX_roots[first_root,:]
root2 =  min(abs(x) for x in CAX_roots2)

或者有更好的方法吗?提前致谢!

如果这个代码

CAX_roots2 = CAX_roots[first_root,:]
root2 =  min(abs(x) for x in CAX_roots2)

与您的程序中显示的完全一样,问题出在 [first_root,:] 中的逗号。您需要将其指定为 [first_root:].

尾随逗号是您指定具有单个元素的元组的方式。

>>> a = 1
>>> b = 1,
>>> type(a)
<type 'int'>
>>> type (b)
<type 'tuple'>
>>> 

但是,正如@Reticality 指出的那样,first_root 是一个浮点数,它不是您想要的索引。

相反,如果您考虑要查找的内容 - 这是不等式 (f(x) >=0) 的区间。所以使用它:

signs = [x >= 0 for x in CAX_roots]
first_root_index = signs.index(True)
second_root_index = signs[first_root_index:].index(False) + first_root_index - 1
first_root = CAX_roots[first_root_index]
second_root = CAX_roots[second_root_index]

如您所见

>>> l = [-2, -1, 0, 2, 3, 0, -1]
>>> v = [x >=0 for x in l]
>>> v
[False, False, True, True, True, True, False]
>>> v.index(True)
2
>>> v[2:].index(False)
4
>>> l[2]
0
>>> l[2+4-1]
0
>>>

为了稳健,您需要处理来自 index() 调用的 ValueError 异常,如果您的数据永远不会变为正数或 return 变为负数。

关闭。由于尾随逗号,您有一个元组作为索引。您可能不希望 first_root 作为索引,因为它是一个浮点数。如果要从列表中删除该值,请执行以下操作:

CAX_roots2 = CAX_roots[:]  # So they don't reference the same object
CAX_roots2.pop(CAX_roots2.index(first_root))  # Pop the first root's index