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)  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM