2013-11-28 36 views
0

我的問題是,我通過可能的勝利(與每個組合的列表裏面)的列表檢查,我有這個,通過勝利名單中的第一個列表進行檢查,所有在它的元素。我怎樣才能讓這個if語句檢查所有元素? E.g所以0代表了勝列表中的所有不同的列表,並檢查他們都用這個連接掙扎4贏

對於x在勝:

if 'x' in wins[0] and wins[0][0] and wins[0][1] and wins[0][2] and wins[0][3] == 'x': 
     print("\nWell done! You've won!") 
     menu(
+0

我想我需要看到更多的程序能夠回答這個問題。一開始什麼是勝利的內容? – ChrisProsser

+0

勝利的內容是在我的6 x 7網格中連續四個不同的組合,這也是名爲「網格」的列表中的6個列表 – Peter

回答

0

這將檢查每個子表的所有項目== X。

wins = [['x', 'x', 0, 'x'], ['x', 0, 0, 'x'], ['x', 'x', 'x', 'x']] 

# Iterate over all sublists 
for win in wins: 
    # Iterate over all elements in list, and check if all equals x 
    if all(i == 'x' for i in win): 
     # If this is the case - write a message and break out of the loop 
     print("Well done! You've won!") 
     break 

如果你想按照你的方式做,你必須解決你的原代碼中的一些問題。你不能說if a and b and c and d == 'x'。這是由Python的interpereted這樣的:

if a is not False and 
    b is not False and 
    c is not False and 
    d == 'x' 

您要檢查各個項目,如:

if wins[0][0] == 'x' and wins[0][1] == 'x' and wins[0][2] == 'x' and wins[0][3] == 'x': 

,然後把所有的這一個循環中:

for sublist in wins: 
    if sublist[0] == 'x' and sublist[1] == 'x' and sublist[2] == 'x' and sublist[3] == 'x': 
     print("Well done! You've won!") 
     break 

但是這非常麻煩 - 您應該使用for循環代替。這是一個可以更清楚的例子:通過在子列表的所有項目通過所有的子列表

for sublist in wins: 
    for item in sublist: 
     if item != 'x' 
      break 
    else: 
     print("Well done! You've won!") 
     break 

此代碼將循環,然後循環。如果遇到一個不等於'x'的項目,則內部循環被破壞。

在for循環的結尾處,有一個else子句。這在Python中很少使用,但可以非常好。 else子句中的代碼只有在循環未被破壞時纔會執行。

在我們的情況下,這意味着所有的項目等於'x'。

+0

我剛剛嘗試過,裝載遊戲時,只要'x'是放置在網格中,它回覆良好,你贏了。需要這樣才能檢測到4個連接的元素 – Peter

+0

這是行得通的,但僅限於獲勝組合[0],它可以達到40個奇數組合 – Peter

+0

非常感謝!這是完美的。一直困擾着我 – Peter