如何使此代码始终为数组中的每个元素返回1个小数?
import numpy as np
def mult_list_with_x(liste, skalar):
print(np.array(liste) * skalar)
liste = [1, 1.5, 2, 2.5, 3]
skalar = 2
mult_list_with_x(liste, skalar)
即:[2.0 3.0 4.0 5.0 6.0]
不是[2.3。4.5。6.]
您可以使用np.set_printoptions
设置格式:
import numpy as np
def mult_list_with_x(liste, skalar):
print(np.array(liste) * skalar)
liste = [1, 1.5, 2, 2.5, 3]
skalar = 2
np.set_printoptions(formatter={'float': '{: 0.1f}'.format})
mult_list_with_x(liste, skalar)
输出:
[ 2.0 3.0 4.0 5.0 6.0]
请注意,此np打印选项设置是永久性的-请参阅下面的临时选项
或者要在之后重置默认值,请使用:
np.set_printoptions(formatter=None)
np.get_printoptions() # to check the settings
临时设置打印选项的选项-kudos to mozway用于注释中的提示!:
with np.printoptions(formatter={'float': '{: 0.1f}'.format}):
print(np.array(liste) * skalar)
仅将打印输出格式化为字符串的选项:
print(["%.1f" % x for x in ( np.array(liste) * skalar)])
输出:
['2.0', '3.0', '4.0', '5.0', '6.0']
选择一个适合如何进一步使用输出的选项。
您需要首先使用此设置:
float_formatter = "{:.1f}".format
np.set_printoptions(formatter={'float_kind':float_formatter})
输出
[2.0 3.0 4.0 5.0 6.0]