小白请教变量匹配和赋值

2018-04-25 13:39:50 +08:00
 mochanight
现某字符串有一个四则运算:
假设如下:
nnn = '(40+26*55)-1102-11'

要为每个数字设置变量,即:
a = 40
b = 26
c = 55
d = 1102
f = 11
要为每个运算符设置变量,即:
a1 = (
a2 = +
a3 = *
a4 = )- #运算符在一起的时候为 1 个变量
a5 = -

还有就是,nnn 有可能是这样的
nnn = '40+26*55-1102-11'

这时第一个字符不是运算符的时候 a1 必须要为空

请教该怎么搞啊??弄了半天 if 头都大了
2096 次点击
所在节点    Python
7 条回复
jmc891205
2018-04-25 14:07:33 +08:00
用正则表达式先把所有的数字搞出来
再用正则表达式把所有的非数字搞出来
nethard
2018-04-25 14:11:03 +08:00
了解一下有限状态机
Sylv
2018-04-25 14:45:25 +08:00
逆波兰表达式了解下。
cfwyy
2018-04-25 15:26:49 +08:00
本来字符和数字匹配用正则都是可以的,不过你是为了什么 ,计算四则运算?
这种还是用 后缀表达式比较好,就是楼上就的逆波兰表达式 可以了解一下。
peinstrike
2018-04-25 18:38:16 +08:00
python cookbook 上有现成的代码。
siteshen
2018-04-26 01:44:28 +08:00
# -*- coding: utf-8 -*-

# 不是很清楚你的需求,写了个函数收集字符串中的连续数字和连续符号,供参考。
def collect(string):
operands = []
operators = []

last_symbol = ''
is_last_digit = False

for s in string:
if is_last_digit:
if s.isdigit():
# both are digist, append
last_symbol += s
else:
# digist and not digist, end scaning
operands.append(last_symbol)
last_symbol = s
else:
if not s.isdigit():
# both are not digist, append
last_symbol += s
else:
# digist and not digist, end scaning
operators.append(last_symbol)
last_symbol = s

is_last_digit = s.isdigit()

# append last symbol
if is_last_digit:
operands.append(last_symbol)
else:
operators.append(last_symbol)

return operands, operators


if __name__ == '__main__':
print(collect('(40+26*55)-1102-11'))
print(collect('40+26*55-1102-11'))

# `for` 和 `# appending last symbol` 后的 `if` 一个缩进层级,其他的缩进层级应该不需要额外的说明。
# 输出结果如下(本地没 python3 )
# (['40', '26', '55', '1102', '11'], ['(', '+', '*', ')-', '-'])
# (['40', '26', '55', '1102', '11'], ['', '+', '*', '-', '-'])
xpresslink
2018-04-26 09:41:48 +08:00
@siteshen
哪用得着那么麻烦啊, 看着都累。

>>> nnn = '(40+26*55)-1102-11'
>>> import re
>>> numbers = re.findall('\d+', nnn)
>>> operators = re.split('\d+', nnn)
>>> [numbers, operators]
[['40', '26', '55', '1102', '11'], ['(', '+', '*', ')-', '-', '']]
>>>

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/449712

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX