python - 将注释放在多行列表文字中

标签 python list comments literals

我正在做一个优化问题并编写一个巨大的列表。我想在列表中插入评论,如下所示

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/

相关文章:

python - 在 Python 中对对象进行排序

python - Twisted (Python) - cooperate 和 coiterate 有什么区别?

python - 如何在python中迭代列表的元组列表,并一一获取所有元素?

python - 嵌套列表理解dict和列表python

java - 在 grails 中减去具有重复元素的列表

linux - 函数声明而不是注释

python - 计算特定列中的重复项

python Flask 应用程序使用 ACR 在 Azure Linux 容器上使用 Datadog 跟踪 APM 日志

templates - Netbeans 6.9.1 编辑方法注释模板

coding-style - 你的 "hard rules"关于评论你的代码是什么?