<p>您可以使用内置的<a href="https://docs.python.org/3/library/functions.html#all" rel="nofollow noreferrer" title="all()">all()</a>函数检查所有元素是否都为True,<br/>
和<a href="https://stackoverflow.com/a/10507199/2049320">Row-to-Column Transposition</a>的<code>zip(*table)</code>符号</p>
<pre><code>mytable1 = [[0,0,0,0],[1,1,1,1],[0,0,0,0],[0,0,0,0]]
mytable2 = [[0,0,1,0],[0,0,1,0],[0,0,1,0],[0,0,1,0]]
mytable3 = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]
mytable4 = [[0,0,0,1],[0,0,1,0],[0,1,0,0],[1,0,0,0]]
mytable5 = [[0,1,0,0],[0,0,1,0],[0,1,0,0],[1,0,0,0]]
mytable6 = [[2,1,0,0],[2,0,1,0],[2,1,0,0],[2,0,1,0]]
mytable7 = [[2,1,0,0],[0,2,1,0],[0,1,2,0],[0,0,1,2]]
def hasWon(table,player_no):
#check rows
for row in table:
if all([e==player_no for e in row]):
return True
#check columns
for column in zip(*table):
if all([e==player_no for e in column]):
return True
#check diagonals
if all([table[i][i]==player_no for i in range(len(table)) ]):
return True
if all([table[-i-1][i]==player_no for i in range(len(table))]):
return True
return False
print(hasWon(mytable1,1))
print(hasWon(mytable2,1))
print(hasWon(mytable3,1))
print(hasWon(mytable4,1))
print(hasWon(mytable5,1))
print(hasWon(mytable6,2))
print(hasWon(mytable7,2))
</code></pre>
<p>输出:</p>
<pre><code>True
True
True
True
False
True
True
</code></pre>