[英]How to split algebraic expressions in a string using python?
例如,我得到以下輸入:
-9x+5x-2-4x+5
我需要得到以下列表:
['-9x', '5x', '-2', '-4x', '5']
這是我的代碼,但我不知道如何處理缺點。
import re
text = '-3x-5x+2=9x-9'
text = re.split(r'\W', text)
print(text)
警告:我不能使用除 re 和 math 之外的任何庫。
您可以re.findall
所有后跟+
或-
(或字符串結尾$
)的字符組,然后從子字符串中strip
+
(與-
一樣,它仍然是以下組的一部分)。
>>> s = "-9x+5x-2-4x+5"
>>> [x.strip("+") for x in re.findall(r".+?(?=[+-]|$)", s)]
['-9x', '5x', '-2', '-4x', '5']
同樣,對於帶有=
的第二個字符串,將其添加到字符組並將其從子字符串中剝離:
>>> s = '-3x-5x+2=9x-9'
>>> [x.strip("+=") for x in re.findall(r".+?(?=[+=-]|$)", s)]
>>> ['-3x', '-5x', '2', '9x', '-9']
或者在通過=
拆分后將原始理解應用於子字符串,具體取決於結果的樣子:
>>> [[x.strip("+") for x in re.findall(r".+?(?=[+-]|$)", s2)] for s2 in s.split("=")]
>>> [['-3x', '-5x', '2'], ['9x', '-9']]
事實上,現在我想到了,你也可以findall
所有匹配一個可選的減號,后跟一些數字和一個可選的x
,有或沒有先用=
分割:
>>> [re.findall(r"-?\d+x?", s2) for s2 in s.split("=")]
[['-3x', '-5x', '2'], ['9x', '-9']]
許多可能的方法之一:
import re
term = "-9x+5x-2-4x+5"
rx = re.compile(r'-?\d+[a-z]?')
factors = rx.findall(term)
print(factors)
這產生
['-9x', '5x', '-2', '-4x', '5']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.