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
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
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']]
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']]
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
>>>