You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Python NumPy数组输出的每个元素始终保留1位小数?

Solution to Force One Decimal Place in NumPy Array Output

Hey there! The issue you're seeing is that NumPy's default print behavior omits trailing .0 for whole numbers when displaying floats. To get every element to show exactly one decimal place, here are two straightforward ways to modify your code:

Method 1: Use NumPy's Print Options

This approach adjusts how NumPy formats all array prints (temporarily or permanently, depending on your needs):

import numpy as np

def mult_list_with_x(liste, skalar):
    result = np.array(liste) * skalar
    # Set formatter to display floats with 1 decimal place
    np.set_printoptions(formatter={'float': '{:.1f}'.format})
    print(result)
    # Optional: Reset to default print options if needed later
    # np.set_printoptions(formatter=None)

liste = [1, 1.5, 2, 2.5, 3]
skalar = 2
mult_list_with_x(liste, skalar)

How it works:

  • np.set_printoptions(formatter={'float': '{:.1f}'.format}) tells NumPy to format every float value using the string format {:.1f}, which ensures exactly one decimal place (including trailing zeros for whole numbers).
  • If you want to avoid changing the global print behavior for other arrays, uncomment the reset line to revert to default settings after printing.

Method 2: Manually Format the Output String

This method builds the output string directly, so it doesn't affect any global NumPy settings:

import numpy as np

def mult_list_with_x(liste, skalar):
    result = np.array(liste) * skalar
    # Format each element to 1 decimal place and construct the output string
    formatted_elements = ['{:.1f}'.format(x) for x in result]
    print(f"[{ ' '.join(formatted_elements) }]")

liste = [1, 1.5, 2, 2.5, 3]
skalar = 2
mult_list_with_x(liste, skalar)

How it works:

  • We iterate over each element in the result array, formatting each to one decimal place with '{:.1f}'.format(x).
  • Then we join these formatted strings with spaces, wrap them in brackets, and print the final string. This gives you full control over the exact output format.

Either of these methods will produce the output you want: [2.0 3.0 4.0 5.0 6.0]

内容的提问来源于stack exchange,提问作者Lars Moe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 13:34:08