src = 'f(x)= x + 2 - 3\nbox = f(2) + 2\nbox = f(f(2)) + 2\nfunc = 3 +
3 * 4\n'
des = []
p = re.compile(r'f\(\d+\)')
pro = src.split('\n')
def f(x):
return eval(pro[0].split('=')[1])
def call_f(match):
x = int(re.search(r'\d+', match.group()).group())
return str(f(x))
for line in pro:
if line.startswith('f(x)'):
continue
else:
while p.search(line):
line = p.sub(call_f, line)
des.append(line)
print '\n'.join(des)
‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’
不过觉得有些不够“精炼”,于是也依葫芦画瓢的写了一个:
‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘
import re
src = 'f(x)= x + 2 - 3\nbox = f(2) + 2\nbox = f(f(2)) + 2\nfunc = 3 +
3 * 4\n'
p = re.compile(r'f\([^()]\)')
n = src.find('\n')
func = src[:n]
content = src[n+1:]
exec func.replace('f(x)=','f=lambda x:')
def call_f(match):
exec 'res='+match.group()
return str(res)
while p.search(content):
content = p.sub(call_f,content)
print content
’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’
看起来似乎好一些了,但总有些不对味的感觉,还远远达不到“精巧”,想请诸位老大给些
提示,看法啥的
-------
最后,还有一个小疑问,由于我的代码是脱胎于第一种,其实里面有一个还没有想明白的东西,
这里的call_f方法中match参数是从哪里产生的啊?不知其所以然啊,难道在sub的时候,自动生成了
这么个玩意?看了re.py,只有个match方法啊,求教Ing...
--
来自: `python-cn`:CPyUG ~ 华蟒用户组 | 发言:pyth...@googlegroups.com
退订: http://tinyurl.com/45a9tb //针对163/qq邮箱:http://tinyurl.com/4dg6hc
详情: https://groups.google.com/group/python-cn
严正: 理解列表! 智慧提问! http://wiki.woodpecker.org.cn/moin/AskForHelp