将Numpy数组转换为列表会打印出额外的零?Python

3
我使用了numpy创建了一个数组,现在需要将每个值转换为字符串列表。
以下是我找到的解决方案:
props = np.arange(0.2,0.5,0.1)
props = [str(i) for i in props]

然而当我打印它时,得到的结果是:
Out[177]: ['0.2', '0.30000000000000004', '0.4000000000000001']]

我想要的结果是['0.2', '0.3', '0.4']

我做错了什么?

有更有效的方法吗,还是这种方法太复杂了?


1
https://floating-point-gui.de - BlackBear
0.30000000000000004.com - Sayandip Dutta
哈哈,我不禁笑了,因为这是许多其他编程新手问过的问题。大家加油! - apang
@apang也许你可以考虑接受你发现有用的答案,这样这个问题就可以关闭了。 - some_programmer
1
是的,我正在尝试接受您下面的答案,但被提示要等待4分钟才能这样做。 - apang
3个回答

1
你可以使用 np.around
import numpy as np

props = np.arange(0.2,0.5,0.1)
props = np.around(props, 1)
props = [str(i) for i in props]

#output
['0.2', '0.3', '0.4']

或者:

props = np.arange(0.2,0.5,0.1)
props = [str(np.around(i, 1)) for i in props]

0

将它们四舍五入

props = np.arange(0.2,0.5,0.1)
props = [str(round(i,2)) for i in props]

['0.2', '0.3', '0.4']

0

除了使用round()函数,您还可以使用这个小技巧:

import numpy as np
props = np.arange(0.2,0.5,0.1)
props = [str(int(i*10)/10) for i in props]
print(props)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接