列表理解可以在pythonshell中使用,但不能在scrip中使用

2024-05-07 08:04:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为bot编写一个数学插件,并在python交互式shell中测试我的代码,该shell正常执行:

>>> 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']

但当我将其包含在脚本中时,它会失败,并出现一个类型错误:

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

Tags: 代码textin脚本插件forlenif
1条回答
网友
1楼 · 发布于 2024-05-07 08:04:20

你发布的代码也不起作用。在交互式解释器中执行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']

相关问题 更多 >