pythonlistzero-padding

Pad float with zeros according to maximum length in list


I have a list:

ls = [1.0, 2.11, 3.981329, -15.11]

I want to add zeros to decimal places of each element so that all values have the same length as the value that has maximum length. So the output should be:

[1.000000, 2.110000, 3.981329, -15.110000]

How can I do this?


Solution

  • Here's an alternative solution. Note that the nums will be strings:

    ls = [1.0, 2.11, 3.981329, -15.11]
    
    dps = lambda x: len(x) - x.index(".") - 1
    
    max_dp = max([dps(str(i)) for i in ls])
    
    new_ls = [f"%.{max_dp}f"%i for i in ls]
    
    print(new_ls)
    

    Output:

    ['1.000000', '2.110000', '3.981329', '-15.110000']