Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round floats in a nested list to 2 decimal places? [duplicate]

I have coordinate lists of several polygons as listed below:

l_b =  [[[57.5, 2.875],
   [83.75, 4.1875],
   [83.75, 18.70923913043478],
   [57.50000000000001, 18.70923913043478],
   [57.5, 2.875]],
  [[83.75, 18.70923913043478],
   [57.50000000000001, 18.70923913043478],
   [57.5, 34.08695652173913],
   [83.75, 34.54347826086956],
   [83.75, 18.70923913043478]],
  [[0.0, 0.0],
   [18.125, 0.90625],
   [18.125, 16.70108695652174],
   [-2.530467720685112, 16.70108695652174],
   [0.0, 0.0]],
  [[18.125, 16.70108695652174],
   [-2.530467720685112, 16.70108695652174],
   [-5.0, 33.0],
   [18.125, 33.40217391304348],
   [18.125, 16.70108695652174]]]

How can I make all the numbers in list to round to 2 decimal places while keeping its format?

I've tried l_b = [ '%.2f' % elem for elem in l_b ] but it's giving me TypeError: must be real number, not list

like image 240
jinha kim Avatar asked Dec 05 '22 08:12

jinha kim


1 Answers

@Guy's solution has one side-effect. It makes list flatten.

This could be more suitable.

l_b = [[['%.2f' % z for z in y] for y in x] for x in l_b]
like image 90
mrEvgenX Avatar answered Dec 10 '22 11:12

mrEvgenX