gpt4 book ai didi

Python 元组超出范围

转载 作者:太空宇宙 更新时间:2023-11-03 23:48:20 25 4
gpt4 key购买 nike

我一直收到错误 IndexError: tuple out of range 我希望你们能帮助我完成我的程序

MIN_ROW = 0
MAX_ROW = 3
MIN_COLUMN = 0
MAX_COLUMN = 19

问题似乎仍然存在于第 7 行

def display(theMap):
r = 0
c = 0
print("PLAYER MAP")
for r in range (0, (MAX_ROW + 1), 1):
for c in range (0, (MAX_COLUMN + 1), 1):
print(theMap[r][c]) #this line
print()
print()

def loadMap():
theMap = []
for r in range(0,(MAX_ROW+1), 1):
theMap.append([])
for c in range(0,(MAX_COLUMN+1), 1):
theMap[r].append(" ")
# 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
map [0] = "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J"
map [1] = "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-"
map [2] = "|r|","| |", "| |", "| |", "| |", "| |", "| |", "| |", "| |", "| |", "|"
map [3] = "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-"
return theMap

所以我不确定我的元组是如何超出范围的,但希望你们能指出并帮助我

最佳答案

用显式循环编写东西通常会导致难以调试的问题。这就是 Python 不强制您这样做的原因,实际上鼓励您不要这样做:

def display(theMap):
print("PLAYER MAP")
for row in theMap:
for col in row:
print(col)
print()
print()

这仍然不是您真正想要的,因为 print(col) 打印换行符。您不希望每个单元格都在自己的行上,您希望单元格之间有空格,并且每一行都在自己的行上。为此,您必须改为 print(col, end=' ')

或者,更简单地说:

def display(theMap):
print("PLAYER MAP")
for row in theMap:
print(' '.join(row))
print()

或者,更简洁——但可能不那么简单:

def display(theMap):
print("PLAYER MAP")
print('\n'.join(' '.join(row) for row in theMap))
print()

您可以通过一次创建 theMap 来类似地改进 theMap,而不是创建空行,然后替换它们。例如:

def loadMap():
return [
("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J"),
("-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-"),
("|r|","| |", "| |", "| |", "| |", "| |", "| |", "| |", "| |", "| |", "|"),
("-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-")]

一般来说,每当您发现自己在 Python 中编写 for i in range(something) 时,您就在做一些不必要的事情,您最终只会调试。

现在,您可能会争辩说这种样式不会“捕获错误”。但是用显式循环做事只能捕获少数错误,并且以一种很难调试的方式捕获它们。如果你知道你的先决条件,你通常可以更简单明了地写它们:

theMap = loadMap()
assert(all(len(row) == len(theMap[0]) for row in theMap))

此外,如果您知道测试用例的输出应该是什么,则可以编写单元测试来验证输出。

无论如何,即使解决了所有这些问题,您仍然会遇到一些问题。例如,除了第 2 行比其他行短几列之外,该行中的各个列是其他行中的 3 倍大,因此它根本不会排成一行。但是一旦你让它运行起来,调试视觉内容应该会更容易。

退后一步,您显然要将“r”推进到第 2 行。事实上,您可能需要表示 map 的只是宽度和当前位置:

def display(mapWidth, playerPosition):
print('PLAYER MAP')
# Display the first line. This is the header, with a label for each of the
# mapWidth columsn, with a space between each label, and an extra space at
# the start, like ' 0 1 2 3 4'. The ' '.join(s) creates a new string by
# putting a space between each element of s. The '012...XYZ'[:mapWidth]
# just takes the first mapWidth characters of the longer string.
print(' ' + ' '.join('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'[:mapWidth]))

# Display the second line. This is just a '-' for each column, with a space
# between each, and an extra space at the start, like ' - - - - -'. The join
# works the same as above; the '-' * mapWidth creates a string with mapWidth
# copies of '-'.
print(' ' + ' '.join('-' * mapWidth))

# Display the third line. This is the trickiest. This is cell for each column,
# where the first playerPosition cells are '| |', the playerPositionth is
# '|r|', and the rest are again '| |', with no space between them. It seemed
# simpler to treat this as a group of playerPosition+1 '|' characters with
# spaces between, an 'r' character, and a group of mapWidth-playerPosition
# '|' characters with spaces between again, but there are various different
# ways of printing something equivalent. The only new thing here is the
# end='' keyword argument--without that, each print ends with a newline.
print(' '.join('|' * (playerPosition + 1)), end='')
print('r', end='')
print(' '.join('|' * (mapWidth - playerPosition)))

# Fourth line, same as the second.
print(' ' + ' '.join('-' * mapWidth))
print()

根据您对 join 方法、print 函数等的熟悉程度,您可能会发现这更容易阅读:

def display(mapWidth, playerPosition):
print('PLAYER MAP')
print(' ' + ' '.join('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'[:mapWidth]))
print(' -' * mapWidth)
print(' '.join('|' * (playerPosition + 1)) +
'r' +
' '.join('|' * (mapWidth - playerPosition)))
print(' -' * mapWidth)
print()

值得思考为什么,例如,' ' + ' '.join('-' * 8)' -' * 8 是同一回事。

还有另一种实现棘手的第三行的方法是:

   # Print mapWidth '|' characters, each followed by a ' ', except for the one
# at the player position, which is followed by an 'r'. Then we still need one
# more '|' at the end.
print(''.join('|' + (' ' if i != playerPosition else 'r')
for i in range(mapWidth) + '|')

我认为这是最容易用英语解释的,但是将其翻译成 Python 需要生成器表达式和三元 if 表达式,您可能还不想学习这两者——最终结果甚至是Python 开发人员可能不想阅读的经验。

当然,当有疑问时,您总是可以将内容拉出到单独的行中,甚至是单独的函数中,以使其更具可读性:

    cellsBeforePlayer = '| ' * playerPosition
cellsWithPlayer = cellsBeforePlayer + '|r|'
cellsToEnd = cellsWithPlayer + '| ' * (mapWidth - playerPosition)
print(cellsToEnd)

无论如何,这些都做同样的事情:

>>> display(MAX_COLUMN - MIN_COLUMN + 1, 3)
PLAYER MAP
0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J
- - - - - - - - - - - - - - - - - - - -
| | | |r| | | | | | | | | | | | | | | | |
- - - - - - - - - - - - - - - - - - - -

除非那些 MIN_COLUMNMAX_COLUMN 值是要求的一部分,否则我将使用单个 COLUMNS=20 变量来代替——同样,它避免了另一种常见的差一错误(函数调用中的 + 1,很容易在需要时忘记包含,或者在不需要时添加错误)。

或者,如果 map 宽度固定,那就更简单了:

def display(playerPosition):
print('PLAYER MAP')
print(' ' + ' '.join('0123456789ABCDEFGHIJ'))
print(' -' * 20)
print(' '.join('|' * (playerPosition + 1)) +
'r' +
' '.join('|' * (20 - playerPosition)))
print(' -' * 20)
print()

无论如何,这样做的优势超出了显示的简单性,而且根本不需要loadMap——来移动播放器,而不是这样:

theMap[2][playerPosition] = '| |'
playerPosition += stepsMoved
theMap[2][playerPosition] = '|r|'
display(theMap)

你只需这样做:

playerPosition += stepsMoved
display(playerPosition)

您的整个游戏状态从一个复杂的列表列表减少到一个整数。

关于Python 元组超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13484814/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com