简体   繁体   English

字符串中所有正数和负数的总和

[英]Sum of all positive and negative numbers in string

I have a string of numbers that have negative and positive numbers like so:我有一串具有负数和正数的数字,如下所示:

number = "17,1,29,17,1,-6,-16,-16,29,3,29,18,3,19,-17,28"

Like this code works, but it ignores negative number as negatives and adds them like positives.就像这段代码一样,它会忽略负数作为负数并将它们添加为正数。 The sum suppose to be 139 and not 114.总和假设为 139 而不是 114。

def sumNumbers(number):
    return sum(int(x) for x in number if x.isdigit())

And I dont know how to fix that.我不知道如何解决这个问题。

Just split by ',' :只需用','分割:

numbers = "17,1,29,17,1,-6,-16,-16,29,3,29,18,3,19,-17,28"
result = sum(map(int, numbers.split(',')))
print(result)

Output Output

139

you can split() the string:你可以 split() 字符串:

number = "17,1,29,17,1,-6,-16,-16,29,3,29,18,3,19,-17,28"

sum = 0
for nr in number.split(','):
    sum+=int(nr)

print(sum)
# 139

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM