How do I get this code to always return 1 decimal for every element in the array?
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)
I.e.: [2.0 3.0 4.0 5.0 6.0]
not [2. 3. 4. 5. 6.]
CodePudding user response:
You can use np.set_printoptions
to set the format:
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)
Output:
[ 2.0 3.0 4.0 5.0 6.0]
Update based on the comments:
An option to just format the print output is (replace the print statement within the function):
print(["%.1f" % x for x in ( np.array(liste) * skalar)])
Output:
['2.0', '3.0', '4.0', '5.0', '6.0']
Choose an option fitting how the output should further be used.
CodePudding user response:
You need to use this setup first:
float_formatter = "{:.1f}".format
np.set_printoptions(formatter={'float_kind':float_formatter})
Output
[2.0 3.0 4.0 5.0 6.0]