码迷,mamicode.com
首页 > 编程语言 > 详细

Python在的if使用

时间:2014-12-28 22:10:35      阅读:313      评论:0      收藏:0      [点我收藏+]

标签:

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)

  

Python在的if使用

标签:

原文地址:http://www.cnblogs.com/lizhaoxian/p/4190596.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!