繁体   English   中英

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

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

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

我如何像这样打印'ANTT'

你可以通过使用来简化很多

>>> 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'

你得到这个输出的原因是因为你打印了一个列表,因为 board 的元素是列表。 通过使用join ,您会得到一个字符串。

另外,如果要更改循环的索引,我不明白为什么要使用循环。

好吧,你得到了你告诉打印的东西!

boardstr的列表,所以board[i]必须是str的列表,当你写print(board[i]) ,你会得到一个列表!

你可能需要这样写:

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

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM