Removing all commas from list in Python

后端 未结 7 942
旧巷少年郎
旧巷少年郎 2021-01-07 12:26

My issue: I\'d like to add all the digits in this string \'1.14,2.14,3.14,4.14\' but the commas are causing my sum function to not work correctly.
I figured

7条回答
  •  死守一世寂寞
    2021-01-07 13:03

    Since there seem to be a pattern in your input list of floats, this one-liner generates it:

    >>> sum(map(float, ','.join(map(lambda x:str(x+0.14), range(1,5))).split(',')))
    10.559999999999999
    

    And since it doesn't make much sense joining with commas and immediately splitting by commas, here's a little saner piece of code:

    >>> sum(map(float, map(lambda x:str(x+0.14), range(1,5))))
    10.559999999999999
    



    And if you actually meant you wanted to sum single digits and not the actual floating-point numbers (although I doubt it since you cast to float in your sample code):

    >>> sum(map(int, ''.join(map(lambda x:str(x+0.14), range(1,5))).replace('.', '')))
    30
    

提交回复
热议问题