Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 列表理解中的else语句出错_Python_List_Loops_If Statement_List Comprehension - Fatal编程技术网

Python 列表理解中的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] ==

我在玩弄列表理解,但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] == '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

的每个迭代值的吗?你想在那里做什么?你想在那里做什么?