例如,我有这三个列表:
r0 = ['X', 'O', 'O']
r1 = ['X', 'X', 'O']
r2 = ['X', '.', 'O']
我想使用像这样的循环:
n = 0
while n < 3:
if r0[n] == r1[n] == r2[n] == "X":
result = "X"
break
elif rn[0] == rn[1] == rn[2] == "O":
result = "O"
break
我需要rn
r0
n == 0
,r1
n == 1
等等。
有办法做到这一点吗?
答案 0 :(得分:2)
你只想要:
for n, rn in enumerate((r0, r1, r2)):
通常,我认为将结构更改为列表列表会更好:
r = [['X', 'O', 'O'],
['X', 'X', 'O'],
['X', '.', 'O']]
然后你的循环是:
for n, rn in enumerate(r):
答案 1 :(得分:0)
你的意思是:
r = [r0, r1, r2]
for n, rn in enumerate(r):
if r0[n] == 'X' and r1[n] == 'X' and r2[n] == 'X':
result = 'X'
break
elif rn[0] == 'O' and rn[1] == 'O' and rn[2] == 'O':
result = 'O'
break
也许更整洁:
rows = [['X', 'O', 'O'],
['X', 'X', 'O'],
['X', '.', 'O']]
for n, row in enumerate(rows):
if all(row[n] == 'X' for row in rows): # shadowing 'row' here, not sure what else you might call it
result = 'X'
break
elif all(r == 'O' for r in row):
result = 'O'
break