Python在的if使用

reference  : https://docs.python.org/3/reference/expressions.html#conditional-expressions

6.11. Conditional expressions

conditional_expression ::=  or_test ["if" or_test "else" expression]
expression             ::=  conditional_expression | lambda_expr
expression_nocond      ::=  or_test | lambda_expr_nocond

Conditional expressions (sometimes called a “ternary operator”) have the lowest priority of all Python operations.

The expression 

x if C else y

  

 first evaluates the condition, C rather than x. If C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.

See PEP 308 for more details about conditional expressions.

 

举例:

1 先判断字符类型,然后把list转换为小写字符的list

L1=[‘Hello‘, ‘World‘, 18, ‘Apple‘, None]
L2=[x.lower() if isinstance(x, str) else x for x in L1]
print (L2)

2 取(0-100)的一个偶数序列

L1=[x for x in range(100) if x%2==0]
print (L1)

  

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。