完成第4章:字符图片网格的练习问题后,我决定尝试打印解决方案的反面。在处理完IndexError并尝试使用try,except循环打印出我的问题所在后,我仍然不知道如何解决IndexError:列表超出范围
grid = [
['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
""" This part of the code prints correctly according to specifications
from ATBS"""
for x in range(len(grid[0])): # prints number of elements in list[0]
for y in range(0, len(grid)): # prints number of lists in list
print(grid[y][x], end='')
print()
#This is my attempt at printing the inverse of the ATBS solution
for x in range(len(grid[0]), -1, -1):
for y in range(len(grid)):
try:
print(grid[y][x], end='')
except IndexError:
print('Out of Range')
print()
预期:
..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....
....O....
...OOO...
..OOOOO..
.OOOOOOO.
.OOOOOOO.
..OO.OO..
实际:
..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....
Out of Range
Out of Range
Out of Range
Out of Range
Out of Range
Out of Range
Out of Range
Out of Range
Out of Range
....O....
...OOO...
..OOOOO..
.OOOOOOO.
.OOOOOOO.
..OO.OO..
答案 0 :(得分:0)
在代码for i in range(6,-1,-1)
中,您将以6
为步长设置-1
的起点,-1
的终点。这将产生7个数字,从6倒数到0。
简单的解决方法是将起点降低1:
for x in range(len(grid[0])-1, -1, -1):
for y in range(len(grid)):
try:
print(grid[y][x], end='')
except IndexError:
print('Out of Range')
print()
答案 1 :(得分:0)
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
def heart(list):
for i in range(len(grid[0])):
for j in range(len(grid)):
print(grid[j][i],end=' ')
print('')
for i in range(len(grid[0])-1,-1,-1):
for j in range(len(grid)):
print(grid[j][i],end=' ')
print('')
print(heart(grid))
. . O O . O O . .
. O O O O O O O .
. O O O O O O O .
. . O O O O O . .
. . . O O O . . .
. . . . O . . . .
. . . . O . . . .
. . . O O O . . .
. . O O O O O . .
. O O O O O O O .
. O O O O O O O .
. . O O . O O . .
None
最后一个'None'为何出现,我不知道。 如果有人知道,请发表评论