我有一个字符串,例如“ 12-569-8”,并希望将其拆分为一个负整数和正整数的列表,以便我可以将它们加在一起-例如
list = ['1', '2', '-5', '6', '9', '-8']
其中的总和为5。我主要是在拆分列表方面苦苦挣扎。
一种可能的方法是使用正则表达式,并同时匹配数字或带负号的数字:
s = "12-569-8"
import re
sum(map(int,re.findall(r'(\d|-\d)', s)))
# 5
另一种方法,如prune在评论中提到的那样,是遍历字符,并根据发现的内容进行加或减:
res = 0
i=0
while i < len(s):
x = s[i]
if x != '-':
res += int(x)
else:
i += 1
res -= int(s[i])
i += 1
print(res)
# 5
如果不想使用导入,则可以用空格分隔所有字符,并在减号后删除空格。然后将字符串分割成空格,每个数字都会正确解释:
s = "12-569-8"
c = " ".join(s).replace("- ","-") # space out, remove space after minus
n = list(map(int,c.split())) # split and convert to integers
print(c) # '1 2 -5 6 9 -8'
print(n) # [1, 2, -5, 6, 9, -8]