慕無忌1623718
2022-07-12 15:49:01
我希望能夠拆分這樣的東西:"20 - 5 - 4 + 10 + 4"要么作為帶符號的數字進入一個列表:["20", "-5", "-4", "+10", "+4"]或進入兩個無符號列表:["20", "10", "4"]
["5", "4"]有沒有我可以在 python 中使用的內置方法?
2 回答

肥皂起泡泡
TA貢獻1829條經驗 獲得超6個贊
您可以使用re.findall:
import re
s = "20 - 5 - 4 + 10 + 4"
new_s = re.findall('[-+]?\d+', s.replace(' ', ''))
輸出:
['20', '-5', '-4', '+10', '+4']

阿波羅的戰車
TA貢獻1862條經驗 獲得超6個贊
如果不存在空格或任何其他運算符,則沒有regex但會中斷。
expr = "20 - 5 - 4 + 10 + 4"
tokens = expr.split()
if tokens[0].isnumeric():tokens = ['+'] + tokens
tokens = [''.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]
添加回答
舉報
0/150
提交
取消