【问题标题】:error with else statement in list comprehension列表理解中的 else 语句出错
【发布时间】:2018-12-15 19:07:41
【问题描述】:

我在玩列表推导,但 else 语句出现语法错误

doctor = ['house', 'cuddy', 'chase', 'thirteen', 'wilson'] 
first = [doc[0] for doc in doctor if doc[0] == 'h' else doc[3]]

这有什么问题?

【问题讨论】:

  • 你想在那里做什么?

标签: python list loops if-statement list-comprehension


【解决方案1】:

你可以试试这个吗?

doctor = ['house', 'cuddy', 'chase', 'thirteen', 'wilson'] 
first = [doc[0] if doc[0] == 'h' else doc[3] for doc in doctor]

【讨论】:

    【解决方案2】:

    以下代码

    doc[0] for doc in doctor if doc[0] == 'h' else doc[3]
    

    大致翻译成

    for doc in doctor
        if doc[0] == 'h'
            doc[0]
    else doc[3]
    

    因此 else 部分没有doc 的定义。正确的代码是

    first = [doc[0] if doc[0] == 'h' else doc[3] for doc in doctor]
    

    其中

    doc[0] if doc[0] == 'h' else doc[3]
    

    是基于doc的每个迭代值的三元条件。

    【讨论】:

      猜你喜欢
      • 2018-09-08
      • 2020-11-15
      • 1970-01-01
      • 1970-01-01
      • 2020-05-13
      • 2018-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多