Python-将数组转换为列表会导致值更改 [英] Python - Converting an array to a list causes values to change

查看:168
本文介绍了Python-将数组转换为列表会导致值更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

it appears that some values in the list have changed and I can't find them with index(). How can I fix that?

推荐答案

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

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

The numbers in the array are rounded for display purposes, but the array really contains the value you subsequently see in the list; 0.6000000000000001. 0.6 cannot be precisely represented as a float, therefore it is unwise to rely on floating-point numbers comparing precisely equal!

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

One way to find the index is to use a tolerance approach:

def float_index(seq, f):
    for i, x in enumerate(seq):
         if abs(x - f) < 0.0001:
             return i

也可以在数组上使用:

>>> float_index(a, 0.6)
3

这篇关于Python-将数组转换为列表会导致值更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆