我可以在Python中的一行中放入一个列表语句和一个if语句吗?

时间:2018-03-21 18:50:36

标签: python if-statement

我试图压缩我的代码并将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

1 个答案:

答案 0 :(得分:1)

这将实现您的目标:

temperature = 10 if 'hi' in ('hi', '2') else 1

顺便说一句,条件'hi' in ('hi', '2')始终是True,它有什么意义?

相关问题