2015-11-19 205 views
5

Python的新手遇到了測試相等的問題。我有一個列表,列出狀態[];每個狀態都包含x,在這個特定情況下x = 3,布爾值。在我的程序中,我生成了一個布爾值列表,其中前三個對應於一個狀態[i]。我循環通過狀態列表測試相等(其中一個肯定是正確的,因爲所有可能的布爾置換都處於狀態,但是等於從未被檢測到。不知道爲什麼,這裏是我修改的一些代碼來測試它:列表是相同的但不相同?

temp1 = [] 
for boolean in aggregate: 
    temp1.append(boolean) 
if len(temp1) == len(propositions): 
    break 
print temp1 
print states[0] 
if temp1 == states[0]: 
    print 'True' 
else: 
    print 'False' 

在這種情況下,propisitons的長度是3。我從這個代碼得到的輸出是:

[True, True, True] 
(True, True, True) 
False 

我猜這與在括號中的差異做一些與事實?狀態[0]是列表中的列表嗎?乾杯。

+3

'states [0]'是一個元組,而不是一個列表。 Brace/parens的風格在Python中非常重要。 –

+0

是的,我現在看到了。我曾使用內置函數來填充狀態,並不知道該函數創建了元組而不是列表;我甚至不知道元組。謝謝,請牢記這一點。 – Bergy24

回答

8

你是c omparing一個元組(True, True, True)針對列表[True, True, True]

當然他們是不同的。

嘗試您鑄造listtuple在這去,來比較:

temp1 = [] 
for boolean in aggregate: 
    temp1.append(boolean) 
if len(temp1) == len(propositions): 
    break 
print temp1 
print states[0] 
if tuple(temp1) == states[0]: 
    print 'True' 
else: 
    print 'False' 

或鑄造你的tuplelist在這去,來比較:

temp1 = [] 
for boolean in aggregate: 
    temp1.append(boolean) 
if len(temp1) == len(propositions): 
    break 
print temp1 
print states[0] 
if temp1 == list(states[0]): 
    print 'True' 
else: 
    print 'False' 

輸出:

[True, True, True] 
(True, True, True) 
True 
+0

我用一個內置的函數來填充狀態[],不知道它們是由元組構成的;我從來沒有使用元組,將不得不閱讀他們,非常感謝。 – Bergy24

+1

@ Bergy24我很高興我的回答有幫助。請不要忘記接受我的答案,如果它幫助你解決問題:) –

相關問題