Python有三元条件运算符吗?

Python有三元条件运算符吗?,python,operators,ternary-operator,conditional-operator,Python,Operators,Ternary Operator,Conditional Operator,如果Python没有三元条件运算符,是否可以使用其他语言构造来模拟一个条件运算符?是的,是在2.5版中。表达式语法为: a如果条件为b 首先计算条件,然后根据条件的值计算并返回a或b中的一个。如果条件的计算结果为真,则计算并返回a,但忽略b,或者计算并返回b,但忽略a 这允许短路,因为当条件为真时,仅计算a,而根本不计算b,但当条件为假时,仅计算b,而根本不计算a 例如: shell = os.environ.get('SHELL', "/bin/sh") >>“true”如果为true,否

如果Python没有三元条件运算符,是否可以使用其他语言构造来模拟一个条件运算符?

是的,是在2.5版中。表达式语法为:

a如果条件为b
首先计算
条件
,然后根据
条件
的值计算并返回
a
b
中的一个。如果
条件
的计算结果为
,则计算并返回
a
,但忽略
b
,或者计算并返回
b
,但忽略
a

这允许短路,因为当
条件
为真时,仅计算
a
,而根本不计算
b
,但当
条件
为假时,仅计算
b
,而根本不计算
a

例如:

shell = os.environ.get('SHELL', "/bin/sh")
>>“true”如果为true,否则为“false”
“真的”
>>>如果为假,则为“真”,否则为“假”
“假”
请注意,条件句是表达式,而不是语句。这意味着您不能在条件表达式中使用赋值语句或
pass
或其他语句

>>如果为False则通过,否则x=3
文件“”,第1行
如果为False,则通过,否则x=3
^
SyntaxError:无效语法
但是,可以使用条件表达式指定变量,如下所示:

x=a如果为真,否则为b
将条件表达式视为在两个值之间切换。当你处于“一种价值观或另一种价值观”的情况下时,它非常有用,但在其他方面却无能为力

如果需要使用语句,则必须使用普通的
If
语句,而不是条件表达式


请记住,由于以下几个原因,一些蟒蛇学家不赞成这种做法:

  • 参数的顺序不同于经典的
    条件?A: B</COD>三元运算符,来自许多其他语言(如C、C++、GO、Perl、Ruby、java、JavaScript等),这可能会导致当人们不熟悉Python的“令人惊讶”行为时使用bug(它们可以颠倒论据顺序)。
    
  • 有些人觉得它“笨拙”,因为它违背了正常的思维流程(先考虑条件,然后考虑效果)
  • 风格上的原因。(虽然“inline
    if
    ”非常有用,可以使脚本更加简洁,但它确实会使代码复杂化)
如果你记不住顺序,记得大声朗读时,你(几乎)说出了你的意思。例如,如果b>8,则x=4,否则9被大声读出,因为如果b大于8,则x将为4,否则9

正式文件:

来自:

在所有Python操作中,条件表达式(有时称为“三元运算符”)的优先级最低

表达式
x如果C或者y
首先计算条件C(不是x);如果C为true,则计算x并返回其值;否则,将计算y并返回其值

有关条件表达式的详细信息,请参见


2.5版之后的新版本。

对于2.5版之前的版本,有一个技巧:

[expression] and [on_true] or [on_false]
on\u true
具有错误的布尔值。1
虽然它确实有从左到右计算表达式的好处,但在我看来这更清楚


一,

您可以索引到元组中:

(falseValue, trueValue)[test]
test
需要返回True或False。
始终按照以下方式实施可能更安全:

(falseValue, trueValue)[test == True]
或者,您可以使用内置来确保值:

(假值,真值)[bool()]
不幸的是

(falseValue, trueValue)[test]
解决方案没有短路行为;因此,
falseValue
trueValue
都会在不考虑条件的情况下进行评估。这可能是次优的,甚至是错误的(即
trueValue
falseValue
都可能是方法,并且有副作用)

解决这个问题的一个办法是

(lambda: falseValue, lambda: trueValue)[test]()
(执行延迟,直到知道获胜者;),但它会在可调用对象和不可调用对象之间引入不一致性。此外,它不能解决使用属性时的情况

故事是这样的——在上述三种解决方案中进行选择是一种权衡,即在具有短路功能、至少使用3ython 2.5(不再是问题)和不容易出现“
trueValue
-评估为假”错误之间进行权衡。

如果存在其他错误

a=1
b=2
1如果a>b,则为-1
#输出为-1
1如果a>b else-1如果a
对于Python 2.5及更新版本,有一个特定的语法:

[on_true] if [cond] else [on_false]
在旧python中,没有实现三元运算符,但可以模拟它

cond and on_true or on_false
但是,存在一个潜在的问题,即如果
cond
的计算结果为
True
on\u True
的计算结果为
False
,则返回
on\u False
,而不是
on\u True
。如果您想要此行为,则方法是确定的,否则使用以下方法:

{True: on_true, False: on_false}[cond is True] # is True, not == True
可通过以下方式包装:

def q(cond, on_true, on_false)
    return {True: on_true, False: on_false}[cond is True]
用这种方式:

q(cond, on_true, on_false)
它与所有Python版本兼容。

您可能经常会发现

cond and on_true or on_false
但当on_true==0时,这会导致问题

>>> x = 0
>>> print x == 0 and 0 or 1 
1
>>> x = 1
>>> print x == 0 and 0 or 1 
1
在这里,对于一个正常的三元运算符,你会期望得到这个结果

>>> x = 0
>>> print 0 if x == 0 else 1 
0
>>> x = 1
>>> print 0 if x == 0 else 1 
1

模拟python三元运算符

比如说

a, b, x, y = 1, 2, 'a greather than b', 'b greater than a'
result = (lambda:y, lambda:x)[a > b]()
输出:

'b greater than a'

Python中的条件表达式的运算符是在2006年作为的一部分添加的。它的形式不同于常见的
?:
运算符,它是:

<expression1> if <condition> else <expression2>
可使用的另一种语法(与2.5之前的版本兼容):

其中操作数为

另一种方法是索引元组(这与大多数其他语言的条件运算符不一致):

if <condition>: <expression1> else: <expression2>
result = x if a > b else y
result = (lambda:y, lambda:x)[a > b]()
result = (y, x)[a > b]
result = {True: x, False: y}[a > b]
result = (a > b) and x or y
result = ((a > b) and [x] or [y])[0]
result = ((a > b) and (x,) or (y,))[0]
shell = os.environ.get('SHELL', "/bin/sh")
test: or_test ['if' or_test 'else' test] | lambdef
or_test ['if' or_test 'else' test]
expression1 if expression2 else expression3
expression1 if expression2 else expression3 if expression4 else expression5 # and so on
[expression1 if expression2 for element in iterable]
#                          ^-- need an else here
[expression1 for element in iterable if expression2]
expression1 if expression1 else expression2
expression1 or expression2
if conditionX:
    print('yes')
else:
    print('nah')
print('yes') if conditionX else print('nah')
var a = true ? 1 : 0;
# 1
var b = false ? 1 : 0;
# 0
a = true ? 1 : 0
# 1
b = false ? 1 : 0
# 0
val a = true ? 1 | 0
# 1
val b = false ? 1 | 0
# 0
a <- if (TRUE) 1 else 0
# 1
b <- if (FALSE) 1 else 0
# 0
a = 1 if True else 0
# 1
b = 1 if False else 0
# 0
0 and exp
1 or exp
True and exp1 or exp2
False and exp1 or exp2
# Program to demonstrate conditional operator
a, b = 10, 20
# Copy value of a in min if a < b else copy b
min = a if a < b else b
print(min)  # Output: 10
# Python program to demonstrate ternary operator
a, b = 10, 20
# Use tuple for selecting an item
print( (b, a) [a < b] )
# Use Dictionary for selecting an item
print({True: a, False: b} [a < b])
# lamda is more efficient than above two methods
# because in lambda  we are assure that
# only one expression will be evaluated unlike in
# tuple and Dictionary
print((lambda: b, lambda: a)[a < b]()) # in output you should see three 10
# Python program to demonstrate nested ternary operator
a, b = 10, 20
print ("Both a and b are equal" if a == b else "a is greater than b"
        if a > b else "b is greater than a")
# Python program to demonstrate nested ternary operator
a, b = 10, 20
if a != b:
    if a > b:
        print("a is greater than b")
    else:
        print("b is greater than a")
else:
    print("Both a and b are equal") 
# Output: b is greater than a
def test(myvar=None):
    # shorter than: print myvar if myvar else "no Input"
    print myvar or "no Input"

test()
test([])
test(False)
test('hello')
test(['Hello'])
test(True)
no Input
no Input
no Input
hello
['Hello']
True
#[On true] if [expression] else[On false]
# if the expression evaluates to true then it will pass On true otherwise On false


a= input("Enter the First Number ")
b= input("Enter the Second Number ")

print("A is Bigger") if a>b else print("B is Bigger")
a if condition else b
     condition
  if           else
a                   b 
<condition> ? <expression1> : <expression2>
<expression1> if <condition> else <expression2>
pressure = 10
print('High' if pressure < 20 else 'Critical')

# Result is 'High'
pressure = 5
print('Normal' if pressure < 10 else 'High' if pressure < 20 else 'Critical')

# Result is 'Normal'
pressure = 5

if pressure < 20:
    if pressure < 10:
        print('Normal')
    else:
        print('High')
else:
    print('Critical')

# Result is 'Normal'
"yes" if boolean else "no"
{True:"yes", False:"no"}[boolean]
{True:"yes", False:"no", None:"maybe"}[boolean_or_none]
("no", "yes")[boolean]
yes() if boolean else no()
(no(), yes())[boolean]  # bad
f = lambda x,y: 'greater' if x > y else 'less' if y > x else 'equal'

array = [(0,0),(0,1),(1,0),(1,1)]

for a in array:
  x, y = a[0], a[1]
  print(f(x,y))

# Output is:
#   equal,
#   less,
#   greater,
#   equal

<expression 1> if <condition> else <expression 2>
is_spacial=True if gender = "Female" else (True if age >= 65 else False)
>>> li1 = None
>>> li2 = [1, 2, 3]
>>> 
>>> if li1:
...     a = li1
... else:
...     a = li2
...     
>>> a
[1, 2, 3]
>>> a = li1 if li1 else li2
>>> 
>>> a
[1, 2, 3]
>>> 
>>> a = li1 or li2
>>> 
>>> a
[1, 2, 3]
>>> 
>>> li1 = []
>>> li2 = [1, 2, 3]
>>> 
>>> a = li1 or li2
>>> 
>>> a
[1, 2, 3]
>>> 
>>> s1 = ''
>>> s2 = 'hello world'
>>> 
>>> a = s1 or s2
>>> 
>>> a
'hello world'
>>> 
iif = lambda (cond, a, b): a if cond else b
# so I can then use it like:
val = iif(cond, a, b)
run_algorithm(option_value if option_value is not None else 10)
run_algorithm(option_value if option_value else 10)
run_algorithm(option_value or 10)
(a := 3) if True else (b := 5)
(a := 3) if False else (b := 5)
c = (a := 3) if False else (b := 5)