【问题标题】:Making a chessboard and i'm getting an IndexError: list index out of range制作棋盘,我得到一个 IndexError: list index out of range
【发布时间】: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


【解决方案1】:

我建议对代码进行一些重组,以便您对每一行的输入进行一次完整的有效性测试,然后我们可以在特定行上构建每个位置的列表,并将其附加到棋盘列表。以下内容完全未经测试,因此如果有语法错误,请告诉我,我会对其进行编辑。

 def is_valid_row(user_in):
    possible_char = ["-","K","k","Q","q","R","r","N","n","B","b","P","p"]
    if len(user_in) != 8:
        print("Please enter a string of 8 characters")
        return False
    for each_char in user_in:
        if each_char not in possible_char:
            print("You have entered illegal char {}".format(each_char))
            return False
    # Neither of those other two have returned false
    # so we're good to assume it's valid
    return True

 def make_a_chessboard():
     chessboard = []
     rows = 8

     # Process each row (you do this line by line, right?)
     for r in range(rows):
        user_input = input("")
        while not is_valid_row(user_input):
             user_input = input("")

        # We now have valid input (or we're stuck in while-loop-hell)
        # break the input into a list (of 8 valid chars)
        each_row = [x for x in user_input]

        # Now append it to chessboard
        chessboard.append(each_row)


    return(chessboard)

【讨论】:

    猜你喜欢
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 2019-02-23
    • 2015-02-11
    相关资源
    最近更新 更多