【问题标题】:Problem with round() when turning a list into an array将列表转换为数组时 round() 的问题
【发布时间】:2021-09-24 00:54:36
【问题描述】:

我创建了一个列表,其中一个元素被四舍五入:

In [1] list = [(0.382, 0.618, round(411.8724133605957,2))]
       list

嗯,作为list 没问题:

Out [1] [(0.382, 0.618, 411.87)]

但是当我使用np.array() 将它变成一个数组时,所有的小数都再次弹出:

In [2] array = np.array(list)
       array

Out [2] array([[3.8200e-01, 6.1800e-01, 4.1187e+02]])

然后我尝试了 np.round()np.around() 到该数组,但什么也没发生:

In [3] np.round(array,2), np.around(array,2)

Out [3] (array([[3.8000e-01, 6.2000e-01, 4.1187e+02]]),
         array([[3.8000e-01, 6.2000e-01, 4.1187e+02]]))

虽然很有趣,但我不明白为什么,以及如何获得如下所示的数组:

array[[0.382, 0.618, 411.87]]

感谢任何想法,谢谢!

【问题讨论】:

  • 这就是数字的表示方式。 4.1187e+02411.87 是相同的数字,以不同的形式打印。要强制后者,请尝试np.set_printoptions(suppress=True)

标签: python arrays list data-structures rounding


【解决方案1】:

这就是numpy表示这些小数的方式,值是一样的。

如果您希望它定期显示,请尝试np.set_printoptions

在你的代码之前,可能在你下面一行numpyimport,添加这行代码:

np.set_printoptions(suppress=True)

然后打印array 将如下所示:

[[   0.382    0.618  411.87 ]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 2022-01-18
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多