+ 1

Data conversion

Hi all, I have a programming task to solve in python. I have a bunch of floats from an app that I need to convert to a readable format for another app. It needs to do a few things (can be done in any order): - read a bunch of floats (could be any amount) in a list - round them to .2 decimal places - if the float is 0.0 (app only gives 0.0), print "0" - replace/remove any symbols with spaces (" ") - no spaces at the last float (space sensitive) - can be printed as strings instead of integer (you can use string formatting) Example: floats = [3.141, 0.0, 2.71828, 1.61, 0.12345678, 0.0, ...] (could contain more than 3 decimal places) round: 3.14, 0.0, 2.72, 1.61, 0.12, 0.0 (printed on each line) zeros: 3.14, 0, 2.72, 1.61, 0.12, 0 (printed on each line) final output: 3.14 0 2.72 1.61 0.12 0 I have a code on this (hopefully this link works) but I want to know if there's a better way to type this. Would like to see your solution in python (and your explanation of it) https://code.sololearn.com/c4CUwulm90l0/#py

28th Apr 2019, 4:22 AM
Roselle Carmen
Roselle Carmen - avatar
4 Answers
+ 2
A couple of steps you described, may be missing (like remove special characters) , because in your example, the floats were already in a list in decent format. It could help if you also provide the original format. If the transformation is more complicated then it could be worth to put it in a separate function that applied to each element with map() like this: https://code.sololearn.com/ck308Hgv9hqp/?ref=app
28th Apr 2019, 5:16 AM
Tibor Santa
Tibor Santa - avatar
+ 3
print(' '.join([f"{i:.2f}","0"][i==0.0]for i in floats)) print(*[[f"{i:.2f}","0"][i==0.0]for i in floats]) print(*[f"{i:.{2*(i!=0.0)}f}"for i in floats])
28th Apr 2019, 4:35 AM
Diego
Diego - avatar
+ 2
' '.join(['0' if f == 0 else str(round(f, 2)) for f in floats])
28th Apr 2019, 4:32 AM
Anna
Anna - avatar
+ 1
@Tibor Santa The "remove special characters" was an instruction of how the final output should be. The original format is already included as an example, where you can edit it into any float array you'd like: floats = [3.141, 0.0, 2.71828, 1.61, 0.12345678, 0.0] If you mean the solution, it was also included as a link. Either that or I'm not sure what did you mean by "original format" Thanks for your contribution.
28th Apr 2019, 5:38 AM
Roselle Carmen
Roselle Carmen - avatar