【发布时间】:2017-08-13 18:36:16
【问题描述】:
目标:将一个空的 ASCII 网格变成一个井字棋盘。 空的时候应该是这样的:
| |
| |
____|________|____
| |
| |
____|________|____
| |
| |
| |
错误:
def myformat(moves, line):
# there's got to be a better way to do this
if line in [1, 4, 7]:
if moves[line] == 'x':
return "\ /"
elif moves[line] == 'o':
return " oo "
elif moves[line] == 'none':
return " "
elif line in [2, 5, 8]:
if moves[line] == x:
return " xx "
elif moves[line] == o:
return "o o"
elif moves[line] == "none":
return " "
elif line in [3, 6]:
if moves[line] == x:
return "/__\b"
elif moves[line] == o:
return "o__o"
elif moves[line] == "none":
return "____"
elif line == 9:
if moves[line] == x:
return "/__\b"
elif moves[line] == o:
return "o__o"
elif moves[line] == "none":
return " "
else:
print("Fatal error.")
>>> moves = ['none']*9
>>> moves
['none', 'none', 'none', 'none', 'none', 'none', 'none', 'none', 'none']
>>> for line in range(1, 10):
print("{}|{}|{}".format((myformat(moves, line))))
Traceback (most recent call last):
File "<pyshell#24>", line 2, in <module>
print("{}|{}|{}".format((myformat(moves, line))))
IndexError: tuple index out of range
full code因为上次有人生气我只发了一部分
我不明白为什么要提到元组。我看到的唯一一个是 range(1, 10) 函数,因为它是一个 for 循环,所以不应该出现索引错误。感谢所有 cmets 和批评。提前致谢。
【问题讨论】:
-
myformat应该返回一个 3-len 元组来馈送format,但它只返回一个字符串。您希望格式可以猜到什么来填充其他字段?也许试试print("{0}|{0}|{0}" -
Python 与大多数编程语言一样,从“0”开始计算索引,而不是从“1”开始计算 - “moves”中的最后一个索引是“8”,而不是“9”。
-
@Jean-FrançoisFabre 你说的很对。我在每个变量上写了
return,当我打算写a='. . . ', b = ' . . . ', c=' . . . ' return a,b,c.之类的东西时,我会改变它,看看它是否能解决问题。 -
很高兴能提供帮助。
标签: python python-3.x for-loop tuples indexoutofboundsexception