【问题标题】:Finding indices of numbers closest to zero (list)查找最接近零的数字的索引(列表)
【发布时间】:2015-04-18 07:39:11
【问题描述】:

我有一个数字列表,当我绘制它们时,我得到了这个大礼帽类型的函数。 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

关于如何找到第二个根的任何帮助/建议?当我尝试从 first_root 值继续迭代到列表末尾时,我似乎无法克服错误“列表索引必须是整数,而不是元组”:

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

或者如果有更好的方法来做到这一点?提前致谢!

【问题讨论】:

  • 这里有一个错误的逗号CAX_roots[first_root,:]
  • 是的,我开始发表评论,但认为作为“年轻球员的陷阱”值得回答

标签: python list loops tuples indices


【解决方案1】:

如果这段代码

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

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

相反,如果您考虑要查找的内容 - 这是不等式 (f(x) &gt;=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 异常,以防您的数据永远不会变为正数或返回负数。

【讨论】:

  • 感谢指正和解释,写的很透彻!我现在明白你对逗号的意思并使用浮点数作为索引了。谢谢!
【解决方案2】:

关闭。由于尾随逗号,您有一个元组作为索引。您可能不希望 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    • 1970-01-01
    • 2020-08-27
    • 2018-01-02
    相关资源
    最近更新 更多