I have the nested list as following:
A=[[2,3.55,40.9998],[53.656,65.9],[0.2222]]
How to round to 2 decimal places for the A, below is my expected output:
A=[[2.00,3.55,41.00],[53.66,65.90],[0.22]]
I try to used round(A,2) but not able, anyone can share me some ideas?
If you need to modify the list, you'll have to iterate over it with either a for loop
for sublst in A:
for i, val in enumerate(sublst):
sublst[i] = round(val, 2)
or a nested list comprehension
new_A = [[round(val, 2) for val in sublst] for sublst in A]
For what it's worth, if you only needed to format for printing, you could use string formatting.
for line in A:
print(" ".join(map("{:.2f}".format, line)))
# equivalent to
print(" ".join([{:.2f}.format(val) for val in line]))
You can go for format function, for example:
a = 2 print(format(a, '.2f'))
The result will be: 2.00
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.