-2

I tried

print("%.2f" % myArray)

and got

TypeError: must be real number, not list

and then I tried

print(map(lambda a: map(lambda x: "%.3f" % x, a), myArray))

and got

SyntaxError: invalid syntax
MSeifert
  • 145,886
  • 38
  • 333
  • 352
Alex R
  • 11,364
  • 15
  • 100
  • 180
  • 1
    If the error message says it doesn't expect a list, then you probably deal with lists here not arrays. It could be useful to clarify that by [edit]ing the post (and including a minimal sample input). – MSeifert Aug 04 '18 at 18:19
  • You can get more insight here: https://stackoverflow.com/questions/21008858/formatting-floats-in-a-numpy-array – Sheldore Aug 04 '18 at 18:23

3 Answers3

1

Just use list comprehension inside a list comprehension:

>>> my_list = [[1.0001, 1.0002], [1.003, 1.004]]
>>> [['{:.2f}'.format(item) for item in sublist] for sublist in my_list]
[['1.00', '1.00'], ['1.00', '1.00']]

I also used str.format instead of the % formatting here. If you're using Python 3.6+ you could also use f-strings for formatting there:

>>> [[f'{item:.2f}' for item in sublist] for sublist in my_list]
[['1.00', '1.00'], ['1.00', '1.00']]

Even with the long variable names it's shorter than a map solution:

>>> list(map(lambda x: list(map(lambda y: "%.2f" % y, x)), my_list))
[['1.00', '1.00'], ['1.00', '1.00']]
MSeifert
  • 145,886
  • 38
  • 333
  • 352
0

Your code works, just remember to list your maps to be able to view in the print

>>> arr = [[1,2,3.22225], [1.31,434.144222]]
>>> print(list(map(lambda a: list(map(lambda x: "%.3f" % x, a)), arr)))

[['1.000', '2.000', '3.222'], ['1.310', '434.144']]
rafaelc
  • 57,686
  • 15
  • 58
  • 82
0

Your map statement is correct for a list. Since you have a 2D array, pass each element of your array (a 1D list) to your map

>>> arr
[[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9], [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]]
>>> print('\n'.join(" ".join(map("{:.2f}".format, lst)) for lst in arr))
0.00 0.10 0.20 0.30 0.40 0.50 0.60 0.70 0.80 0.90
0.00 0.10 0.20 0.30 0.40 0.50 0.60 0.70 0.80 0.90
>>> 
Sunitha
  • 11,777
  • 2
  • 20
  • 23