我想将列表转换为字符串以进行作业。我可以转换 1 行,但是我的老师希望我们转换 3 个单独的行来为生命游戏制作一个网格。我已经尝试了我的代码的许多不同迭代,我得到的最接近的是打印顶行。
我添加了老师希望每行做什么,所以它应该更容易解释
def gridToString( grid ):
# create an empty string
mystr = ' '
# for each row in the grid, convert that row
for row in grid:
mystr += int(input(row))
# for each cell in the row, convert the cell
for cell in row:
mystr += int(input(cell))
# add symbol to the string for this cell
# symbol + for cells that hold a zero
if cell == 0:
cell = '+'
# letter O for cells that are non-zero
elif cell == 1:
cell = 'O'
# add a newline to the string at the end of the grid row
print(mystr, '\n')
# return the string representation of the grid
return mystr
lifeGrid = [[1,1,1],
[0,0,0],
[0,0,1]]
# convert the grid to a string
gridStr = gridToString( lifeGrid )
# print the string!
print( gridStr )
print('')
您的尝试中存在几个问题:
该函数不应调用
input()
,也不应调用 print()
。该函数的目的是将作为参数给出的矩阵转换为字符串并返回该字符串。此操作不涉及任何用户输入,也不输出到终端。因此,删除所有 input()
和 output()
调用。
空字符串是
''
,而不是 ' '
。
无法工作:此赋值的右侧必须是字符串数据类型,因此 c
print(mystr, '\n')
不会改变 mystr
。按照上面评论所说的去做,你应该做mystr += '\n'
mystr += int(input(row))
和mystr += int(input(cell))
都无法工作:这些赋值的右侧必须是字符串,因此调用int()
(返回整数)是错误的。
mystr += int(input(row))
没有做任何有用的事情。 mystr
将在该语句下面的循环中获取该行的内容,因此应该删除该语句。
mystr += int(input(cell))
应改为 mystr += str(cell)
,但请参阅下一点
更改
cell
的代码是无用的,因为在更改之后,这个新值没有执行任何操作:
if cell == 0:
cell = '+'
elif cell == 1:
cell = 'O'
此外,如果
cell
不是 0,那么它预计为 1,所以不需要用 elif cell == 1
检查——这是唯一剩下的可能性。所以把它设为else
。
所以这样做:
if cell == 0:
mystr += '+'
else:
mystr += 'O'
或更短,使用
cell
作为索引:
mystr += '+O'[cell]
这取代了之前对
mystr
的分配。
修正了这些点后,你会得到这个:
def gridToString(grid):
# not a space, but a really emmpty string:
mystr = ''
for row in grid:
# don't ask for input and don't print
for cell in row:
# assign to mystr the character that corresponds to cell
mystr += '+O'[cell]
# add a newline to the string (don't print)
mystr += '\n'
return mystr
现在就可以了。您的问题没有解释字符串末尾是否应该有
\n
。可能只需要行之间。
请注意,按如下方式执行更符合Python风格:
def gridToString(grid):
return '\n'.join(
''.join('+O'[cell] for cell in row)
for row in grid
)
这里我省略了最后的
\n