我在python函数中做错了什么?

时间:2012-11-10 14:20:09

标签: python python-3.x

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])

这会打印['A', 'N', 'T', 'T']

如何以'ANTT'方式打印它?

3 个答案:

答案 0 :(得分:1)

您可以使用

简化整个过程
>>> 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'

您获得该输出的原因是因为您打印列表,因为电路板的元素是列表。通过使用join,您将获得一个字符串。

另外,我不明白你为什么要使用循环来改变你循环的索引。

答案 1 :(得分:1)

嗯,你得到了你要打印的内容!

boardstr列表的列表,因此board[i]必须是str的列表,当您撰写print(board[i])时,您得到一个清单!

您可能需要写下这个:

print(''.join(board[i]))

答案 2 :(得分:0)

我认为这就是你想要做的事情:

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,