Python - 将数组转换为列表会导致值发生变化

pom*_*pum -1 python arrays numpy list

>>> import numpy as np
>>> a=np.arange(0,2,0.2)
>>> a
array([ 0. ,  0.2,  0.4,  0.6,  0.8,  1. ,  1.2,  1.4,  1.6,  1.8])
>>> a=a.tolist()
>>> a
[0.0, 0.2, 0.4, 0.6000000000000001, 0.8, 1.0, 1.2000000000000002, 1.4000000000000001, 1.6, 1.8]
>>> a.index(0.6)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 0.6 is not in list
Run Code Online (Sandbox Code Playgroud)

似乎列表中的某些值已更改,我无法找到它们index().我该如何解决这个问题?

jon*_*rpe 5

0.6没有改变; 它永远不会存在:

>>> import numpy as np
>>> a = np.arange(0, 2, 0.2)
>>> a
array([ 0. ,  0.2,  0.4,  0.6,  0.8,  1. ,  1.2,  1.4,  1.6,  1.8])
>>> 0.0 in a
True # yep!
>>> 0.6 in a
False # what? 
>>> 0.6000000000000001 in a
True # oh...
Run Code Online (Sandbox Code Playgroud)

为了显示目的,数组中的数字是四舍五入的,但数组实际上包含您随后在列表中看到的值; 0.6000000000000001.0.6不能精确地表示为浮点数,因此依靠浮点数来比较精确相等是不明智的!

查找索引的一种方法是使用容差方法:

def float_index(seq, f):
    for i, x in enumerate(seq):
         if abs(x - f) < 0.0001:
             return i
Run Code Online (Sandbox Code Playgroud)

这也适用于阵列:

>>> float_index(a, 0.6)
3
Run Code Online (Sandbox Code Playgroud)