2014-05-23 18 views
3
>>> list1 = ['yes', 'yeah'] 
>>> list2 = ['no', 'nope'] 
>>> 'no' in list2 
True 
>>> 'no' in list1 
False 
>>> 'no' in (list1, list2) 
False 
>>> 'no' in (list1 and list2) 
True 
>>> 'yes' in (list1 and list2) 
False #want this to be true 
>>> 'yes' in (list1 or list2) 
True 
>>> 'no' in (list1 or list2) 
False #want this to be true 
>>> 

正如你所看到的,我無處可去。如果x位於多個列表中的任何一箇中,我該如何返回True?

我該如何使它返回true,如果x或y在任一列表中?

+0

我認爲將上面使用的所有右側參數輸入到python解釋器中以查看它們返回的內容是非常有用的。這可能會幫助你理解爲什麼這些方法都不起作用。 – DaoWen

回答

10

你可以做,使用any

>>> any('yes' in i for i in (list1, list2)) 
True 

或者,正好連接列表:

>>> 'yes' in list1+list2 
True 
+0

我是一個沒有考慮串接的笨蛋。謝謝! – Peaser

+0

@Peaser,沒問題。很高興我能幫到 – sshashank124

2

使用any function

>>> any('no' in x for x in (list1, list2)) 
True 
3

我覺得這裏簡潔的代碼和效率之間的最佳平衡可能會被使用itertools.chain

import itertools 
'no' in itertools.chain(list1, list2) 

chain函數返回產生連續每個列表值的迭代器。結果類似於將所有列表連接在一起,但沒有實際創建一個大量列表的額外開銷。

另一個優點是,你可以通過列表的列表,以chainunpack it with the * operator

all_lists = [list1, list2] 
'no' in itertools.chain(*all_lists) 
+0

而不是'itertools.chain(* all_lists)',你應該使用'itertools.chain.from_iterable(all_lists)'。 –

+0

@SvenMarnach - 我在文檔中看到過(以前從未使用過),但它似乎只是爲了支持無限迭代器而添加的。否則有顯着的性能差異?我只偶爾使用Python,但如果沒有嚴重的性能影響,似乎堅持'*'會更「pythonic」。 – DaoWen

+1

使用'*'強制立即評估外部迭代器。使用'itertools.chain.from_iterable()'來評估一切懶惰。對於應該用於泛型迭代器的代碼,這是可取的。如果你知道你在中型列表上操作,這並不重要。 –

1

any一般是要走的路,但也有這個簡單的表達:

>>> x = 'yes' 
>>> (x in list1) or (x in list2) 
True 
>>> x = 'yep' 
>>> (x in list1) or (x in list2) 
False 

如果x處於list1中,則這具有對錶達式進行快速切割評估的優點,而any方法將每次迭代兩個列表。

相關問題