我經常發現自己寫這樣的代碼檢查多個元素:風格在Python序列
tupla = (1, 2, 3, 4)
if (1 in tupla) and (4 in tupla):
...
有沒有更簡潔寫任何Python的方式,而無需輸入兩次tupla
?
我經常發現自己寫這樣的代碼檢查多個元素:風格在Python序列
tupla = (1, 2, 3, 4)
if (1 in tupla) and (4 in tupla):
...
有沒有更簡潔寫任何Python的方式,而無需輸入兩次tupla
?
if all(x in tupla for x in list_of_x):
或
if set(list_of_x).issubset(set(tupla)):
第一個將盡快停止爲第一x
不tupla
。第二個將在任何情況下創建兩套。
你的代碼是要求實質上是
是[1,4]一子集的
tupla
?
您可以直接表達了這個問題:
In [14]: set([1, 4]).issubset(tupla)
Out[14]: True
In [15]: set([1, 4, 7]).issubset(tupla)
Out[15]: False
,或者更簡潔:
In [18]: set([1, 4]) <= set(tupla)
Out[18]: True
In [19]: set([1, 4, 7]) <= set(tupla)
Out[19]: False
感謝您的解釋。我希望我可以接受多個有效的答案。 – 2011-12-15 13:30:12
現在,我將使用第二個選項,但第一個會派上用場的時候`list_of_x`很長。 – 2011-12-15 13:27:01