Removing all commas from list in Python

后端 未结 7 887
旧巷少年郎
旧巷少年郎 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

    You don't want strip, you want split.

    The split function will separate your string into an array, using the separator character you pass to it, in your case split(',').

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-07 13:05

    Use this to remove commas and white spaces

    a = [1,2,3,4,5]
    print(*a, sep = "")
    

    Output:- 12345

    0 讨论(0)
  • 2021-01-07 13:10

    I would use the following:

    # Get an array of numbers
    numbers = map(float, '1,2,3,4'.split(','))
    
    # Now get the sum
    total = sum(numbers)
    
    0 讨论(0)
  • 2021-01-07 13:11
    values=input()         
    l=values.split(",")   
    print(l)
    

    With values=1,2,3,4,5

    the result is ['1','2','3','4','5']

    0 讨论(0)
  • 2021-01-07 13:22

    You need split not strip.

    >>> for c in '1,2,3,4,5,6,7,8,9'.split(","):
        print float(c)
    
    1.0
    2.0
    3.0
    4.0
    5.0
    6.0
    7.0
    8.0
    9.0
    

    Or if you want a list comprehension:

    >>> [float(c) for c in '1,2,3,4,5,6,7,8,9'.split(",")]
    [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
    

    And for getting the sum,

    >>> sum(map(float, '1,2,3,4,5,6,7,8,9'.split(",")))
    45.0
    
    0 讨论(0)
提交回复
热议问题