python数组转换为列表,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 "", line 1, in

ValueError: 0.6 is not in list

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 hasn't changed; it was never there:

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

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

which will work on the array too:

>>> float_index(a, 0.6)

3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值