【发布时间】:2018-05-15 01:38:15
【问题描述】:
标题 我目前正在尝试让用户使用破折号 (-) 和对应于棋子的字母来输入棋盘。但是列表没有正确保存。这是搞砸的代码。
def make_a_chessboard():
chessboard = []
possible_char = ["-","K","k","Q","q","R","r","N","n","B","b","P","p"]
rows = 8
cols = 8
for r in range(rows):
user_input = input("")
while len(user_input) != 8:
print("That is not the correct length. Please try again.")
user_input = input("")
for i in range(len(user_input)):
flag1 = False
while flag1 == False:
if user_input[i] not in possible_char:
print("One of the characters used is not supported. Please try again.")
user_input = input("")
else:
for c in range(cols):
chessboard[r][c].append(user_input[c])
flag1 = True
return(chessboard)
这给了我 IndexError: list index out of range 错误。我做错了什么?
【问题讨论】:
-
哪行代码产生了错误?
-
Traceback(最近一次调用最后):文件“a81.py”,第 73 行,在
main() 文件“a81.py”,第 69 行,在 main user_chessboard = make_a_chessboard()文件“a81.py”,第 30 行,在 make_a_chessboard chessboard[r][c].append(user_input[c]) IndexError: list index out of range -
能否也包含一份您正在尝试的输入的副本?
-
我将输入带有破折号或字母的 8 行代码。输入只是一行破折号,例如“--------”或“--k-K-Q-”
-
哦,我明白了。我期待一个列表分配错误,但因为 append 是一种让列表索引超出范围的方法。这是因为 chessboard[r] 不会退出,因此 chessboard[r][c] 永远不会退出。
标签: list python-3.5 index-error