有点或逗号时如何在 PEP8 中使用反斜杠?

How to use backslash in PEP8 when there is a dot or comma?

这是我的数据框:

In [1]: import pandas as pd
In [2]: df = pd.DataFrame({'col1':['A','A','A','B','B','B'], 'col2':['C','D','D','D','C','C'], 
            'col3':[.1,.2,.4,.6,.8,1]})
In [3]: df
Out[4]: 
  col1 col2  col3
0    A    C   0.1
1    A    D   0.2
2    A    D   0.4
3    B    D   0.6
4    B    C   0.8
5    B    C   1.0

我的问题是:当我想对长文本进行换行时,反斜杠放在哪里?点之后还是点之前?哪个是正确的?

# option 1 backslash after dot or comma
df.groupby('col1').\
    sum()
df['col1'],\
    df['col2']

# option 2 backslash before dot or comma
df.groupby('col1')\
    .sum()
df['col1']\
    ,df['col2']

我还发现,如果我使用括号,则不必使用反斜杠。那么哪个选项是正确的呢?

# option 1: no backslash and dot or comma in the new line
(df.groupby('col1')
    .sum())
(df['col1']
    ,df['col2'])

# option 2: no backslash and dot or comma in the old line
(df.groupby('col1').
    sum())
(df['col1'],
    df['col2'])

# option 3: backslash after dot or comma 
(df.groupby('col1').\
    sum())
(df['col1'],\
    df['col2'])

# option 4: backslash before dot or comma 
(df.groupby('col1')\
    .sum())
(df['col1']\
    ,df['col2'])

说明

PEP8 prefers usage of brackets over backslashes where it's possible.

PEP8 没有说明点或逗号需要与表达式位于同一行(尽管在给定的每个示例中都是如此)。

解决方案

技术上正确的答案是:

# option 1: no backslash and dot or comma in the new line
(df.groupby('col1')
    .sum())
(df['col1']
    ,df['col2'])

# option 2: no backslash and dot or comma in the old line
(df.groupby('col1').
    sum())
(df['col1'],
    df['col2'])

尽管 one could argue that the recommendation against space between a trailing comma and closing parenthesis is the exception that proves the rule,这意味着:,df['col2'] 不符合标准(尽管 , df['col2'] 仍然符合标准)。

尽管上面提供的 2 个选项在技术上是正确的,但以下是最常用 使用的选项:

(df.groupby('col1')
    .sum())
(df['col1'],
    df['col2'])

Note: the indentation depends in the context it's used. The examples above shouldn't be used as reference. Also remember that PEP8 is just a guideline, there are many scenarios where the rules should be broken in order to improve readability.