2016-07-01 5 views
4

ループから3つの特定の部分文字列を持つURLが必要です。次のコードは、働いていたが、私はそれを行うには、よりエレガントな方法があります確信しています:複数のNOT IN文をPythonで使用する

for node in soup.findAll('loc'): 
    url = node.text.encode("utf-8") 
    if "/store/" not in url and "/cell-phones/" not in url and "/accessories/" not in url: 
     objlist.loc.append(url) 
    else: 
     continue 

ありがとうございました! docsから

+1

すべて組み込み関数 –

答えて

6
url = node.text.encode("utf-8")  
sub_strings = ['/store','/cell-phones/','accessories'] 

if not any(x in url for x in sub_strings): 
    objlist.loc.append(url) 
else: 
    continue 

:反復可能なの任意の要素がtrueの場合

anyはTrueを返します。 iterableが空の場合はFalseを返します。同等物:

def any(iterable): 
    for element in iterable: 
     if element: 
      return True 
    return False 
+1

ブームを使用できます。ありがとう、イアン! – tnoznisky

+2

また、de Morgan変換を適用せず、 'すべて(xはサブストリングのxのためのURLにない)'を実行することもできません。 – user2357112