首页 > 代码库 > Python在的if使用
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_exprexpression_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)
Python在的if使用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。