【问题标题】:Syntax error in Python for-if list comprehension loopPython for-if 列表理解循环中的语法错误
【发布时间】:2021-04-21 13:52:28
【问题描述】:

将前导和数据省略到以下内容,因为它看起来像列表理解的编写方式错误。它旨在循环遍历pandas DataFrames 和Series 的列表l,并根据它们是二维(索引和列)还是一维(仅索引)来标记它们。为什么会出现错误(即使关闭换行符)?

[pd.DataFrame(A, index=labels, columns=labels) for A in l 
            if type(A) is pd.DataFrame else pd.Series(A, index=labels)]

结果

    if type(A) is pd.DataFrame else pd.Series(A, index=tickers)]
                                  ^
SyntaxError: invalid syntax

【问题讨论】:

  • 过滤子句在列表理解中仅是if。您实际上要做的是在主子句中使用条件表达式。

标签: python pandas loops syntax-error list-comprehension


【解决方案1】:

是你的问题不是由于是。 也许尝试使用 isinstance(type(A) , pd.DataFrame) 另一点是您的列表理解顺序,如果认为它应该是

[f(x) if condition else g(x) for x in sequence]

所以你可以试试

[pd.DataFrame(A, index=labels, columns=labels) if isinstance(type(A) , pd.DataFrame) else pd.Series(A, index=labels) for A in l ]

【讨论】:

    【解决方案2】:

    您需要将for A in l 移动到语句的末尾。

    [pd.DataFrame(A, index=labels, columns=labels) if type(A) is pd.DataFrame else pd.Series(A, index=labels) for A in l]
    

    见:Is it possible to use 'else' in a list comprehension?

    【讨论】:

      猜你喜欢
      • 2016-05-29
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      相关资源
      最近更新 更多