Python | Ways to format elements of given list
Given a List of float values, the task is to truncate all float values to 2-decimal digit. Let’s see the different methods to do the task.
Method #1 : Using List comprehension
Python3
# Python code to truncate float # values to 2-decimal digits. # List initialization Input = [ 100.7689454 , 17.232999 , 60.98867 , 300.83748789 ] # Using list comprehension Output = [ "%.2f" % elem for elem in Input ] # Printing output print (Output) |
Output:
['100.77', '17.23', '60.99', '300.84']
Method #2 : Using Map
Python3
# Python code to truncate float # values to 2 decimal digits. # List initialization Input = [ 100.7689454 , 17.232999 , 60.98867 , 300.83748789 ] # Using map Output = map ( lambda n: "%.2f" % n, Input ) # Converting to list Output = list (Output) # Print output print (Output) |
Output:
['100.77', '17.23', '60.99', '300.84']
Method #3 : Using format
Python3
# Python code to truncate float # values to 2 decimal digits. # List initialization Input = [ 100.7689454 , 17.232999 , 60.98867 , 300.83748789 ] # Using format Output = [ '{:.2f}' . format (elem) for elem in Input ] # Print output print (Output) |
Output:
['100.77', '17.23', '60.99', '300.84']
Method #4 : Using Iteration
Python3
# Python code to truncate float # values to 2 decimal digits. # List initialization Input = [ 100.7689454 , 17.232999 , 60.98867 , 300.83748789 ] # Output list initialization Output = [] # Iterating for elem in Input : Output.append( "%.2f" % elem) # Printing output print (Output) |
Output:
['100.77', '17.23', '60.99', '300.84']
Method #5 : Using reduce
- This code imports the functools module and uses its reduce function to apply a lambda function to each element in the list Input.
- The lambda function takes in 2 arguments: acc (short for accumulator) and x, and adds the string representation of x with 2 decimal points to acc.
- The initial value of acc is an empty list.
- The reduce function iteratively applies the lambda function to each element in Input, starting with the initial value of acc and the first element of Input, and then using the result of the previous iteration as the new value of acc for the next iteration.
- The final result of the reduce function is the list of strings with 2 decimal points for each element in Input.
Python3
import functools Input = [ 100.7689454 , 17.232999 , 60.98867 , 300.83748789 ] #The reduce function iteratively applies the lambda function to each element in Input, starting with the initial value #of acc and the first element of Input, and then using the result of the previous iteration as the new value of acc for the next iteration. Output = functools. reduce ( lambda acc, x: acc + [ "%.2f" % x], Input , []) print (Output) #This code is contributed by Edula Vinay Kumar Reddy |
Output
['100.77', '17.23', '60.99', '300.84']
Please Login to comment...