将字符串拆分为正数和负数python?

我希望能够拆分这样的东西:

"20 - 5 - 4 + 10 + 4"

要么作为带符号的数字进入一个列表:

["20", "-5", "-4", "+10", "+4"]

或进入两个无符号列表:

["20", "10", "4"]
["5", "4"]

有没有我可以在 python 中使用的内置方法?


慕无忌1623718
浏览 165回答 2
2回答

肥皂起泡泡

您可以使用re.findall:import res = "20 - 5 - 4 + 10 + 4"new_s = re.findall('[-+]?\d+', s.replace(' ', ''))输出:['20', '-5', '-4', '+10', '+4']

阿波罗的战车

如果不存在空格或任何其他运算符,则没有regex但会中断。expr = "20 - 5 - 4 + 10 + 4"tokens = expr.split()if tokens[0].isnumeric():tokens = ['+'] + tokenstokens = [''.join(t) for t in zip(*[iter(tokens)]*2)]pos = [t.strip('+') for t in tokens if '+' in t]neg = [t.strip('-') for t in tokens if '-' in t]或按照@Sayse建议:tokens = expr.replace('- ','-').replace('+ ','+').split()pos = [t.strip('+') for t in tokens if '-' not in t]neg = [t.strip('-') for t in tokens if '-' in t]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python