Issue
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.]
Solution
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]
Note that this np printoptions setting is permanent - see below for a temporary option.
Or to reset the defaults afterwards use:
np.set_printoptions(formatter=None)
np.get_printoptions() # to check the settings
An option to temporarily set the print options - kudos to mozway for the hint in the comments!:
with np.printoptions(formatter={'float': '{: 0.1f}'.format}):
print(np.array(liste) * skalar)
An option to just format the print output as string:
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.
Answered By - MagnusO_O
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.