【问题标题】: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的每个迭代值的三元条件。