2017-02-23 133 views
-2

我有,我有if語句學習Python中使用的情況下:Python的簡化if語句邏輯

if ([Team1_matches[0]>Team2_matches[0] and Team1_matches[1]>Team2_matches[1] and Team1_matches[2]>Team2_matches[2] and 
Team1_matches[3]>Team2_matches[3] and Team1_matches[4]>Team2_matches[4]]): 
winner="Team 1" 
elif ([Team2_matches[0]>Team1_matches[0] and Team2_matches[1]>Team1_matches[1] and Team2_matches[2]>Team1_matches[2] and 
    Team2_matches[3]>Team1_matches[3] and Team2_matches[4]>Team1_matches[4] ]): 
winner="Team 2" 
else:winner="it was a draw or something went wrong" 

它總是返回出於某種原因隊1由於我可憐的組合,請諮詢我如何能實現對於贏家的真正價值,而不必如果多條線路,如果這是正確的程序,我會做到這一點,就需要諮詢

如果沒有括號

if Team1_matches[0]>Team2_matches[0] and Team1_matches[1]>Team2_matches[1] and Team1_matches[2]>Team2_matches[2] and 
                                ^

信達xError:無效的語法

我得到的輸入是這樣的:

Team1_matches[0] = input("Enter the score that team 1 got on match 1? ") 
+0

什麼輸入?爲什麼在你的條件下有'[]'? – depperm

+4

如果條件不符,請移除大括號。 'if([...]):' - >'if ...:'。實際上,您正在檢查布爾值列表的真值,它總是「真」,因爲它不是空的。 –

+0

你也應該看看[如何並行迭代兩個列表](http://stackoverflow.com/questions/1663807/how-can-i-iterate-through-two-lists-in-parallel-in-python )。 –

回答

1

由於Rawing在評論中說,您對您的檢查和非空列表不需要括號被認爲是True。有關更多信息,請參閱the Python documentation

試試這個:

Team1_matches=[1,2,3,4,5] 
Team2_matches=[5,5,5,5,6] 
if (Team1_matches[0]>Team2_matches[0] and Team1_matches[1]>Team2_matches[1] and Team1_matches[2]>Team2_matches[2] and Team1_matches[3]>Team2_matches[3] and Team1_matches[4]>Team2_matches[4]): 
    winner="Team 1" 
elif (Team2_matches[0]>Team1_matches[0] and Team2_matches[1]>Team1_matches[1] and Team2_matches[2]>Team1_matches[2] and Team2_matches[3]>Team1_matches[3] and Team2_matches[4]>Team1_matches[4]): 
    winner="Team 2" 
else: 
    winner="it was a draw or something went wrong" 

print(winner) 

>>> Team 2 
+0

謝謝,那麼列表中最好的方式或價值是什麼?或者在你填寫的數字背後有什麼邏輯? – Ridah

+0

這取決於您的實施。我只是輸入值來測試。你如何得到這些列表? – Avantol13

+0

對不起,將在第一篇文章中加入它。 – Ridah

1

該解決方案使用內置all功能:

Team1_matches = [1,2,3,4,5] 
Team2_matches = [2,3,4,5,6] 

r = range(0, len(Team1_matches)) # range size 

if all(Team1_matches[i] > Team2_matches[i] for i in r): 
    winner="Team 1" 
elif all(Team2_matches[i] > Team1_matches[i] for i in r): 
    winner="Team 2" 
else: 
    winner="it was a draw or something went wrong" 

print(winner) # outputs: "Team 2" 
+0

當我只爲我的代碼添加'all'時,我得到了這個:TypeError:'bool'對象是不可迭代的 – Ridah

+0

不*只添加到您的代碼* - 使用我的代碼 – RomanPerekhrest

+0

我的意思是,添加'all'和elif,所以如果我使用,如果所有從你的代碼我得到上面的錯誤。 – Ridah