[英]List comprehension works in Python shell, but not inside a script
我正在为机器人编写数学插件,并在正常执行它的python交互式外壳中测试我的代码:
>>> text = "!math 0.023*67"
>>> string1 = [b for b in a for a in text.split("!math ") if len(a) != 0]
>>> print string1
['0', '.', '0', '2', '3', '*', '6', '7']
但是,当我将其包含在脚本中时,它将失败并显示TypeError:
Traceback (most recent call last):
File "/Users/ema/Openshift/pythonbot/plugins/math/math.py", line 61, in <module>
string1 = [b for b in a for a in text.split("!math ") if len(a) != 0]
NameError: name 'a' is not defined
您发布的代码也不起作用。 在交互式解释器中输入del a
,然后尝试再次运行它。 您会看到它失败:
>>> text = "!math 0.023*67"
>>> [b for b in a for a in text.split("!math ") if len(a) != 0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
您将循环的顺序弄混了。 从左到右按嵌套顺序列出它们:
[b for a in text.split("!math ") if len(a) != 0 for b in a]
现在无需预先定义即可a
:
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> text = "!math 0.023*67"
>>> [b for a in text.split("!math ") if len(a) != 0 for b in a]
['0', '.', '0', '2', '3', '*', '6', '7']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.