从Python中删除列表中的所有逗号

时间:2013-04-01 17:18:57

标签: python

我的问题:我想在此字符串'1.14,2.14,3.14,4.14'中添加所有数字,但逗号会导致我的总和功能无法正常工作。
我认为使用条带函数可以解决我的问题,但似乎仍然有一些我缺少或不太了解。

total = 0
for c in '1.14,2.14,3.14'.strip(","):
    total = total + float(c)
print total

我已经搜索了如何从字符串中删除逗号,但我只找到了有关如何从字符串的开头或结尾删除逗号的信息。

其他信息:Python 2.7

8 个答案:

答案 0 :(得分:7)

我会使用以下内容:

# Get an array of numbers
numbers = map(float, '1,2,3,4'.split(','))

# Now get the sum
total = sum(numbers)

答案 1 :(得分:4)

您不希望strip,您需要split

split函数会将您的字符串分隔为数组,使用您传递给它的分隔符,在您的情况split(',')中。

答案 2 :(得分:1)

您需要split而不是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

或者如果你想要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]

获得总和,

>>> sum(map(float, '1,2,3,4,5,6,7,8,9'.split(",")))
45.0

答案 3 :(得分:1)

list 中删除逗号

针对 Python3 更新:

a = [1,2,3,4,5]
b = ''.join(str(a).split(','))

从列表中删除逗号,即

[1,2,3,4,5]  --> [1 2 3 4 5]

答案 4 :(得分:0)

这会在你问题的第一个字符串中添加所有数字:

sum(float(x) for x in '1.14,2.14,3.14,4.14' if x.isdigit())

答案 5 :(得分:0)

由于你的浮动输入列表中似乎有一个模式,这个单行代码生成它:

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

因为加入逗号并立即用逗号分割是没有多大意义的,所以这里有一些更安全的代码:

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



如果你真的想要你想要对单个数字求和而不是实际的浮点数(虽然我怀疑它是因为你在示例代码中转换为float):

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

答案 6 :(得分:0)

values=input()         
l=values.split(",")   
print(l)

值= 1,2,3,4,5

结果是['1','2','3','4','5']

答案 7 :(得分:0)

使用它删除逗号和空格

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

输出:- 12345

相关问题