Python 列表理解中的else语句出错
我在玩弄列表理解,但else语句出现语法错误Python 列表理解中的else语句出错,python,list,loops,if-statement,list-comprehension,Python,List,Loops,If Statement,List Comprehension,我在玩弄列表理解,但else语句出现语法错误 doctor = ['house', 'cuddy', 'chase', 'thirteen', 'wilson'] first = [doc[0] for doc in doctor if doc[0] == 'h' else doc[3]] 这有什么问题吗?你能试试吗 doctor = ['house', 'cuddy', 'chase', 'thirteen', 'wilson'] first = [doc[0] if doc[0] ==
doctor = ['house', 'cuddy', 'chase', 'thirteen', 'wilson']
first = [doc[0] for doc in doctor if doc[0] == 'h' else doc[3]]
这有什么问题吗?你能试试吗
doctor = ['house', 'cuddy', 'chase', 'thirteen', 'wilson']
first = [doc[0] if doc[0] == 'h' else doc[3] for doc in doctor]
你能试试这个吗
doctor = ['house', 'cuddy', 'chase', 'thirteen', 'wilson']
first = [doc[0] if doc[0] == 'h' else doc[3] for doc in doctor]
下面的代码
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[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
的每个迭代值的吗?你想在那里做什么?你想在那里做什么?