如何让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
相关产品推荐
相关产品推荐

