2016-06-19 57 views
-1

我想創建一個程序,它需要八個列表中的任何一個等於一個單獨的列表。我有幾個變量列表:testC1,testC2等,並XWIN,以及作爲一個字符串:導致這很難解釋,所以這裏的代碼:Python:比較相同的列表

result = ("n") 
print ("testD1 is:",str(testD1)) #Debugging 
print ("xwin is:",str(xwin)) #Debugging 
if (testC1 or testC2 or testC3 or testR1 or testR2 or testR3 or testD1 or testD2) == (xwin): 
    result = ("x") 
else: 
    pass 
print (result) #Debugging 

,並運行代碼時,我得到以下結果:

>>> testD1 is: ['x', 'x', 'x'] 
>>> xwin is: ['x', 'x', 'x'] 
>>> n 

我希望得到「X」作爲結果,我只是想檢查列表(在這種情況下,testD1)的一個(或多個),以等同於「XWIN」。

我知道這將有可能通過一系列的if,elif語句,但我相信一定有辦法做到這一點,而不是做得更好。我只是不確定在這種情況下的語法。

任何幫助將不勝感激。

+1

使用'any' – dawg

+2

你的邏輯if語句是不是你期待發生什麼。你想要的是沿着'if(testC1 == xwin)或(testC2 == xwin)或''行的東西。你現在的邏輯實際上是把'testC1,testC2,...'列表和'xwin'進行比較。 – user2027202827

+0

您可能會遇到比此更多的問題。你保證有8個列表,還是最大數量的列表? – Thecor

回答

1

非空列表計算爲True在布爾值的上下文,因此,例如,如果您有:

([] or ['a', 'b', 'c'] or ['x', 'x', 'x']) == (['x', 'x', 'x']) 

條件的左側部分將導致['a', 'b', 'c']這不等於['x', 'x', 'x']

然後做你想做什麼,你可以在同一個列表理解取代

(testC1 or testC2 or testC3 or testR1 or testR2 or testR3 or testD1 or testD2) == (xwin) 

通過

xwin in (testC1, testC2, testC3, testR1, testR2, testR3, testD1, testD2)