If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Yes, you can use it that way :
Yes:
Let’s say you want to give variable x some value if some bool is true and likewise
X = 5 if something else x = 10
X = [some value] if [if this is true first value evaluates] else [other value evaluates]
expression1 if condition else expression2
Yes, it was added in version 2.5.
The syntax is:
First
condition
is evaluated, then eithera
orb
is returned based on the Boolean value ofcondition
If
condition
evaluates toTrue
,a
is returned, elseb
is returned.For example:
Note that conditionals are an expression, not a statement. This means you can't use assignments or
pass
or other statements in a conditional:In such a case, you have to use a normal
if
statement instead of a conditional.Keep in mind that it's frowned upon by some Pythonistas for several reasons:
If you're having trouble remembering the order, then remember that if you read it out loud, you (almost) say what you mean. For example,
x = 4 if b > 8 else 9
is read aloud asx will be 4 if b is greater than 8 otherwise 9
.Official documentation:
An operator for a conditional expression in Python was added in 2006 as part of Python Enhancement Proposal 308. Its form differ from common
?:
operator and it's:which is equivalent to:
Here is an example:
Another syntax which can be used (compatible with versions before 2.5):
where operands are lazily evaluated.
Another way is by indexing a tuple (which isn't consistent with the conditional operator of most other languages):
or explicitly constructed dictionary:
Another (less reliable), but simpler method is to use
and
andor
operators:however this won't work if
x
would beFalse
.A possible workaround is to make
x
andy
lists or tuples as in the following:or:
If you're working with dictionaries, instead of using a ternary conditional, you can take advantage of
get(key, default)
, for example:Source: ?: in Python at Wikipedia
From the documentation:
New since version 2.5.