Python 3元组超出范围错误。但我在用字典?

2024-09-27 00:14:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我的战舰计划有个元组超出了射程。我困惑的原因是我没有使用元组,除非我错了,我愿意被纠正。元组是不可变的,它所指的字典在启动程序时会向其中添加项。 我是初学者,所以如果我犯了一个愚蠢的错误,请不要评判!在

from random import randint
#empty list to generate the board.
board = []
messages = {
  "win" : "Nooo you won!",
  "lose" : "Not my ship haha",
  "out" : "Oops, that's not even in the ocean.",
  "repeat" : "You guessed that one already"

}

ships = {
  'shiprows' : [0]
  'shipcols' : [0]
}

#generate board and append to board[] As of now it is a 10*10 grid.
for x in range(0, 10):
  board.append(["O"] * 10)

#prints the board every turn.
def print_board(board):
  for row in board:
    print(" ".join(row))

print_board(board)

#computer chooses where to put battleships' rows
def random_row1(board):
  return randint(0, len(board) - 1)

def random_col1(board):
 return randint(0, len(board) - 1)
#calling above two functions and storing their values for 5 ships.
#creating variables for 5 ships.
vars = 0
for vars in range(0, 5):
  print(vars)
  if len(ships.keys()) >= 4:
    while ships["shiprow{}".format(vars - 2)] == ships["shiprow{}".format(vars - 1)] and ships["shipcol{}".format(vars - 2)] == ships["shipcol{}".format(vars - 1)]:
      ships["shiprow{}".format(vars)] = random_row1(board)
      ships["shipcol{}".format(vars)] = random_col1(board)
    ships["shiprow{}".format(vars)] = random_row1(board)
    ships["shipcol{}".format(vars)] = random_col1(board)
  else:
    ships["shiprow{}".format(vars)] = random_row1(board)
    ships["shipcol{}".format(vars)] = random_col1(board)


#program itself
turn = 0
#enforces four turns before game over. Will possibly extend to unlimited with multiple ships.
print(ships)
for turn in range(20):
  turn = turn + 1
  print ("Turn {}".format(turn))
  print ("Ships Left: {}".format(int(len(ships.keys()) / 2))) 
  guess_row = int(input("Guess Row: "))
  guess_col = int(input("Guess Col: "))

#checking stuff.
  i = 0
  if guess_row == ships["shiprow{}".format(i = range(0, 10))] and guess_col == ships["shipcol{}".format(i)]:
    print (messages["win"])
    board[guess_col][guess_row] = u"#"
    print_board(board)

  elif board[guess_col][guess_row] == "X":
    print ("You guessed that one already.")
  elif guess_row not in range(len(board)) and guess_col not in range(len(board[0])):
    print(messages["out"])
  else:
    print(messages["lose"])
    board[guess_col][guess_row] = "X"
    print_board(board)
  if turn >= 20:
    print ("Game Over")
    board[ships["ship_col{}".format(range(0, 10))]][ships["ship_row{}".format(range(0, 10))]] = u"#"
    print_board(board)
    break

可疑线似乎是第62行-这一行看起来很粗略,但实际上我不知道怎么做。请给出建议: 顺便说一句,错误是:

^{pr2}$

谢谢。在


Tags: inboardformatforlenrangecolrandom
2条回答

每当您使用带有位置格式规范的格式字符串(如{}{1}),但只传递关键字参数时,就会收到此错误消息。在

类似地,如果只使用关键字格式规范的格式字符串(如{v}),但只传递位置参数,则会得到一个KeyError

>>> '{}'.format(i=1)
IndexError: tuple index out of range
>>> '{i}'.format(1)
KeyError: 'i'

解决方法就是让你的规格与你的参数相匹配。不管你喜欢哪种方式都可以,它们只需保持一致:

^{pr2}$

尽管如此,我不知道这有什么意义:

"shiprow{}".format(i = range(0, 10))

你可以用任何一种方法来修复它,但这真的是你想要的字符串吗?在

>>> "shiprow{i}".format(i = range(0, 10))
'shiprowrange(0, 10)'
>>> "shiprow{}".format(range(0, 10))
'shiprowrange(0, 10)'

如果您很好奇为什么会出现这个错误,将format简单化了一点,它是这样工作的:

def format(self, *args, **kwargs):
    result = ''
    index = 0
    bits = self.parse_format_stuff()
    for bit in bits:
        if bit is a regular string:
            result += bit
        elif bit is empty braces:
            result = args[index]
            index += 1
        elif bit is a number in braces:
            result += args[number]
        elif bit is a valid identifier string in braces:
            result += kwargs[identifier]
        else:
            raise a ValueError
    return result

所以,当它看到{}格式规范时,它会查找args[0]。因为没有传递任何位置参数,args是空元组(),所以{}是IndexError。在

可以说,如果format处理这些错误并将它们转化为更好的东西可能会更好,但有时能够以编程方式处理KeyError会很有用。(不经常使用IndexError,但显然两者必须以相同的方式工作。)

获取:

Traceback (most recent call last):
File "shiptest.py", line 51, in <module>
ships['shiprows'][vars] += random_row1(board)
IndexError: list index out of range

从将var=0后的所有内容更改为:

^{pr2}$

我想我把字典里的单子弄错了。 我应该使用.append()吗? 编辑:我用了.append()我是个白痴。它正在工作谢谢你的帮助!在

相关问题 更多 >

    热门问题