我试图压缩我的代码并将if-else语句放在单行上。当我尝试为包含列表内语句的if-else语句执行此操作时,我收到错误。
temperature = 10 if 'hi' in ['hi','2'] else temperature = 1
File "<ipython-input-2-af6c452397be>", line 1
temperature = 10 if 'hi' in ['hi','2'] else temperature = 1
^
SyntaxError: can't assign to conditional expression
答案 0 :(得分:1)
这将实现您的目标:
temperature = 10 if 'hi' in ('hi', '2') else 1
顺便说一句,条件'hi' in ('hi', '2')
始终是True
,它有什么意义?