Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in Python, how to convert list of float numbers to string with certain format?

I have a list of tuple of float numbers, something like

[ (1.00000001, 349183.1430, 2148.12222222222222), ( , , ), ..., ( , ,) ]

How can I convert all numbers to strings, with same format (scientific notation with 8 decimal point precision), while maintaining the same structure (list of tuples, or list of lists)?

I think I can do it with nested for loops, but is there a simpler way such as using map somehow?

like image 831
LWZ Avatar asked Dec 05 '22 11:12

LWZ


1 Answers

Assuming you have some list-of-lists or list-of-tuples:

lst = [ [ 1,2,3 ], [ 1e6, 2e6, 3e6], [1e-6, 2e-6, 3e-6] ]

You can create a parallel list-of-lists using list comprehension:

str_list = [['{0:.8e}'.format(flt) for flt in sublist] for sublist in lst]

Or a list-of-tuples:

str_list = [tuple('{0:.8e}'.format(flt) for flt in sublist) for sublist in lst]

Then, if you'd like to display this set of numbers:

str_display = '\n'.join(' '.join(lst) for lst in strlist)
print str_display
like image 170
Robᵩ Avatar answered Jan 21 '23 06:01

Robᵩ