How to round each item in a list of floats to 2 decimal places?

前端 未结 6 2086
有刺的猬
有刺的猬 2021-01-31 07:20

I have a list which consists of float values but they\'re too detailed to proceed. I know we can shorten them by using the (\"%.f\" % variable) operator, like:

6条回答
  •  感动是毒
    2021-01-31 07:58

    You can use the built-in map along with a lambda expression:

    my_list = [0.2111111111, 0.5, 0.3777777777]
    my_list_rounded = list(map(lambda x: round(x, ndigits=2), my_list))
    my_list_rounded                                                                                                                                                                                                                 
    Out[3]: [0.21, 0.5, 0.38]
    

    Alternatively you could also create a named function for the rounding up to a specific digit using partial from the functools module for working with higher order functions:

    from functools import partial
    
    my_list = [0.2111111111, 0.5, 0.3777777777]
    round_2digits = partial(round, ndigits=2)
    my_list_rounded = list(map(round_2digits, my_list))
    my_list_rounded                                                                                                                                                                                                                 
    Out[6]: [0.21, 0.5, 0.38]
    

提交回复
热议问题