zoukankan      html  css  js  c++  java
  • Python in/not in --- if not/if + for...[if]...构建List+ python的else子句

    区分几个容易出错的地方:

    in 成员运算符 - 如果字符串中包含给定的字符返回 True
    >>>"H" in a True
    not in 成员运算符 - 如果字符串中不包含给定的字符返回 True
    >>>"M" not in a True

    代码中经常会有变量是否为None的判断,有三种主要的写法:

    第一种是`if x is None`;

    第二种是 `if not x:`;

    第三种是`if not x is None`(这句这样理解更清晰`if not (x is None)`) 。

    if x is not None`是最好的写法,清晰,不会出现错误,以后坚持使用这种写法。

    使用if not x这种写法的前提是:必须清楚x等于None,  False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行

          在python中 None,  False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()都相当于False 

    因此在使用列表的时候,如果你想区分x==[]和x==None两种情况的话, 此时`if not x:`将会出现问题:

    >>> x = []  
    >>> y = None  
    >>>   
    >>> x is None  
    False  
    >>> y is None  
    True  

    x=None
    if x is None:
    print("x is None!")

    if not x:
    print("not x !")

    if not x is None:
    print("not x is None!")
    if x is not None:
    print("x is not None! ")

    y=[]
    if y is not None:
    print(" y is not None !")
    if not y:
    print(" not y !")
    输出:
    x is None!
    not x !
    y is not None !
    not y !

    也许你是想判断x是否为None,但是却把`x==[]`的情况也判断进来了,此种情况下将无法区分。

    对于习惯于使用if not x这种写法的pythoner,必须清楚x等于None,  False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行。 

          而对于`if x is not None`和`if not x is None`写法,很明显前者更清晰,而后者有可能使读者误解为`if (not x) is None`,因此推荐前者,同时这也是谷歌推荐的风格

    • for...[if]...构建List (List comprehension)

    1.简单的for...[if]...语句
    Python中,for...[if]...语句一种简洁的构建List的方法,从for给定的List中选择出满足if条件的元素组成新的List,其中if是可以省略的。下面举几个简单的例子进行说明。

    >>> a=[12,3,4,6,7,13,21]  
    >>> newList =[x for x in a]  
    >>> newList  
    [12,3,4,6,7,13,21]  
    >>> newList2 =[x for x in a ifx%2==0]  
    >>> newList2  
    [12,4,6]  

    省略if后,newList构建了一个与a具有相同元素的List。但是,newList和a是不同的List。执行b=a,b和newList是不同的。newList2是从a中选取满足x%2==0的元素组成的List。如果不使用for...[if]..语句,构建newList2需要下面的操作。

    >>> newList2=[]  
    >>>for x in a:  
    ... if x %2==0:  
    ...    newList2.append(x)  
    >>> newList2  
    [12,4,6]  

    2.嵌套的for...[if]...语句
    嵌套的for...[if]...语句可以从多个List中选择满足if条件的元素组成新的List。

    • 善用python的else子句

    1.配合for/while循环语句使用
    在for循环语句的后面紧接着else子句,在循环正常结束的时候(非return或者break等提前退出的情况下),else子句的逻辑就会被执行到。先来看一个例子

    def print_prime(n):  
      for i in xrange(2, n):  
        # found = True  
        for j in xrange(2, i):  
          ifi %j ==0:  
             # found = False   
            break  
        else:  
          print"{} it's a prime number".format(i)  
        # if found:  
             # print "{} it's a prime number".format(i)  
  • 相关阅读:
    03 在百度地图上定位到指定位置
    01 如何将百度地图加入IOS应用程序?
    三个字理解委托机制
    iOS 应用程序打包、真机调试 方法
    在读iOS官方文档时,里面有很多你不懂的单词,不要担心
    用“大控件”与“大数据类型”思想来理解view Cotroller
    04 将当前位置用大头针标注到百度地图上
    02 使用百度地图获得当前位置的经纬度
    专注分享思考过程
    像孙正义为了练英语坚决不说日语一样。我也应该有坚决不看中文文档的心!
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/6305684.html
Copyright © 2011-2022 走看看