标签:
reference : https://docs.python.org/3/reference/expressions.html#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)
标签:
原文地址:http://www.cnblogs.com/lizhaoxian/p/4190596.html