【问题标题】:Printing array indices with the corresponding value in Python在 Python 中打印具有相应值的数组索引
【发布时间】:2020-01-07 02:54:54
【问题描述】:

我在打印带有我想要查找的值的数组索引时遇到问题。我只得到第一个索引,而不是其他索引。

我尝试过使用 np.where 函数,但它不起作用,所以我不得不手动创建一个循环。

代码如下:

g = 0.34
while g <= 0.97: 
        idx = []
        for i in range (0, y2.size):
            if y2[i] == g:
                idx.append(i)
        print(idx)
        g = g + 0.01

这就是我所拥有的:

[92, 376]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
.....

该数组有 500 个值,从 0.34 到 0.97。 与没有循环的 np.where(y2 == g) 相同的输出。

【问题讨论】:

  • 在您的情况下,y2 是什么?这是一个典型的列表吗?

标签: python arrays loops indexing


【解决方案1】:

您遇到了float 的错误。另请参阅专门处理该问题的 this 帖子。简而言之,这就是您的代码中发生的情况:

>>>g = 0.34
>>>g = g + 0.01
>>>g
Out: 0.35000000000000003   

如果与0.35 相比,结果0.35000000000000003 将不再计算为true。尝试改用np.isclose,因为它会处理这些小错误:

>>>import numpy as np
>>>g = 0.34
>>>g = g + 0.01
>>>g==0.35
Out: False
>>>np.isclose(g,0.35)
Out: True

您甚至可以将它与 np.where 结合使用,以让您的原始方法发挥作用:

>>>import numpy as np
>>>g = 0.34
>>>y2 = np.array([0.37, 0.38, 0.37, 0.35, 0.34, 0.34])
>>>np.where(np.isclose(y2,g))
Out: (array([4, 5], dtype=int64),)
>>>g = g + 0.01
>>>np.where(np.isclose(y2,g))
Out: (array([3], dtype=int64),)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 2014-09-23
    • 1970-01-01
    • 2019-09-26
    相关资源
    最近更新 更多