我正在做一个优化问题并编写一个巨大的列表。我想在列表中插入评论,如下所示
my_rhs = [1.0, 1.0, 0.0, 0.0, 0.0,\ #comment1
-1.0, -1.0, -1.0,\ #comment2
0.0, 0.0, 0.0]
但是当我这样做时,Python 会报错。我如何在显示的地方发表评论?我尝试将每一行定义为一个新列表并使用 +
进行追加,但这似乎也不起作用。如下图
my_rhs = [1.0, 1.0, 0.0, 0.0, 0.0]+\ #comment1
[-1.0, -1.0, -1.0]+\ #comment2
[0.0, 0.0, 0.0]
如何在 Python 不报错的情况下在显示的位置进行评论?
最佳答案
您只需删除反斜杠字符:
my_rhs = [1.0, 1.0, 0.0, 0.0, 0.0, # comment1
-1.0, -1.0, -1.0, # comment2
0.0, 0.0, 0.0]
下面是一个演示:
>>> my_rhs = [1.0, 1.0, 0.0, 0.0, 0.0, # comment1
... -1.0, -1.0, -1.0, # comment2
... 0.0, 0.0, 0.0]
>>> my_rhs
[1.0, 1.0, 0.0, 0.0, 0.0, -1.0, -1.0, -1.0, 0.0, 0.0, 0.0]
>>>
\
字符告诉 Python 以下行是当前行的一部分。因此,它解释为:
my_rhs = [1.0, 1.0, 0.0, 0.0, 0.0,\ #comment1
-1.0, -1.0, -1.0,\ #comment2
0.0, 0.0, 0.0]
等价于此:
my_rhs = [1.0, 1.0, 0.0, 0.0, 0.0, #comment1 -1.0, -1.0, -1.0, #comment2 0.0, 0.0, 0.0]
值得注意的是PEP 8 ,Python 代码的官方风格指南,有一个关于包装长行的部分:
The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.
此节选自Explicit Line Joining也是相关的:
A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.
关于python - 将注释放在多行列表文字中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24813982/