没有 else 的 Python 三元运算符 [英] Python Ternary Operator Without else
本文介绍了没有 else 的 Python 三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在 Python 的一行中完成此操作?
if <条件>:myList.append('myString')
我尝试过三元运算符:
myList.append('myString' if )
但是我的 IDE (MyEclipse) 不喜欢它,没有 否则
.
解决方案
是的,您可以这样做:
<条件>和 myList.append('myString')
如果
为假,则短路将启动并且不会评估右侧.如果
为真,则将评估右侧并附加元素.
我只想指出,执行上述操作是非常非pythonic的,无论如何,最好编写此代码:
if : myList.append('myString')
演示:
<预><代码>>>>我的列表 = []>>>False 和 myList.append('myString')错误的>>>我的列表[]>>>True 和 myList.append('myString')>>>我的列表['我的字符串']Is it possible to do this on one line in Python?
if <condition>:
myList.append('myString')
I have tried the ternary operator:
myList.append('myString' if <condition>)
but my IDE (MyEclipse) didn't like it, without an else
.
解决方案
Yes, you can do this:
<condition> and myList.append('myString')
If <condition>
is false, then short-circuiting will kick in and the right-hand side won't be evaluated. If <condition>
is true, then the right-hand side will be evaluated and the element will be appended.
I'll just point out that doing the above is quite non-pythonic, and it would probably be best to write this, regardless:
if <condition>: myList.append('myString')
Demonstration:
>>> myList = []
>>> False and myList.append('myString')
False
>>> myList
[]
>>> True and myList.append('myString')
>>> myList
['myString']
这篇关于没有 else 的 Python 三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文