[英]What i did wrong in my python function?
def make_str_from_row(board, row_index):
''' (list of list of str, int) -> str
Return the characters from the row of the board with index row_index
as a single string.
>>> make_str_from_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 0)
'ANTT'
'''
for i in range(len(board)):
i = row_index
print(board[i])
This prints ['A', 'N', 'T', 'T']
这将打印
['A', 'N', 'T', 'T']
How do I print it like this 'ANTT'
instead?我如何像这样打印
'ANTT'
?
You could simplify that a whole lot by using你可以通过使用来简化很多
>>> def make_str_from_row(board, row_index):
... print repr(''.join(board[row_index]))
...
>>> make_str_from_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 0)
'ANTT'
The reason you get that output is because you print a list since the elements of board are lists.你得到这个输出的原因是因为你打印了一个列表,因为 board 的元素是列表。 By using
join
, you get a string.通过使用
join
,您会得到一个字符串。
Also, I don't understand why you use a loop if are going to change the index you loop over.另外,如果要更改循环的索引,我不明白为什么要使用循环。
Well, you got what you told to print!好吧,你得到了你告诉打印的东西!
board
is a list of list of str
s, so board[i]
must be a list of str
s, and when you write print(board[i])
, you get a list! board
是str
的列表,所以board[i]
必须是str
的列表,当你写print(board[i])
,你会得到一个列表!
You may need to write this:你可能需要这样写:
print(''.join(board[i]))
I think this was what you were trying to do:我认为这就是你想要做的:
def make_str_from_row(board, row_index):
''' (list of list of str, int) -> str
Return the characters from the row of the board with index row_index
as a single string.
>>> make_str_from_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 0)
'ANTT'
'''
for cell in board[row_index]:
print cell,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.