3

I made an array using numpy, and need to convert each value into a string list.

This is the solution I found that worked :

props = np.arange(0.2,0.5,0.1)
props = [str(i) for i in props]

However when I print it out this is the result:

Out[177]: ['0.2', '0.30000000000000004', '0.4000000000000001']]

The result I want is ['0.2', '0.3', '0.4'].

What am I doing wrong?

Is there a more efficient way of doing this or is this a convulated way?

F Blanchet
  • 1,430
  • 3
  • 21
  • 32
apang
  • 93
  • 1
  • 12

3 Answers3

1

You can use np.around:

import numpy as np

props = np.arange(0.2,0.5,0.1)
props = np.around(props, 1)
props = [str(i) for i in props]

#output
['0.2', '0.3', '0.4']

Or:

props = np.arange(0.2,0.5,0.1)
props = [str(np.around(i, 1)) for i in props]
some_programmer
  • 3,268
  • 4
  • 24
  • 59
0

Just round them up

props = np.arange(0.2,0.5,0.1)
props = [str(round(i,2)) for i in props]

['0.2', '0.3', '0.4']
Shahir Ansari
  • 1,682
  • 15
  • 21
0

Beside the round()- function you can just use use this little workaround:

import numpy as np
props = np.arange(0.2,0.5,0.1)
props = [str(int(i*10)/10) for i in props]
print(props)
tifi90
  • 403
  • 4
  • 13