计算python for循环中的混淆

Hom*_*ani 0 python for-loop list count nested-lists

你好,我正在学习 python,我对 python for 循环的计数感到困惑。

我正在实现函数make_str_from_column:这会从列表列表中创建一个字符串,表示一列。

我不明白的是,当我将计数设置为 0 时,我收到一条错误消息。当我将计数设置为 -1 时它有效吗?将不胜感激您的反馈,非常感谢。

这是错误信息

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    make_str_from_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 1)
  File "/Users/<name>/Downloads/a3.py", line 77, in make_str_from_column
    new_element = board[count][column_index]
IndexError: list index out of range
>>> 
Run Code Online (Sandbox Code Playgroud)

这是函数

def make_str_from_column(board, column_index):
    """ (list of list of str, int) -> str

    Return the characters from the column of the board with index column_index
    as a single string.

    >>> make_str_from_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 1)
    'NS'
    >>> make_str_from_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 2)
    'TO'
    >>> make_str_from_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 3)
    'TB'
    >>> make_str_from_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 0)
    'AX'
    >>> make_str_from_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B'], ['X', 'S', 'O', 'B']], 1)
    'NSS'
    """

    # intialise a count for the loop
    count = -1

    # create an empty list to save the indexed elemenets into
    new_list = []

    for i in board:
        count = count + 1
        new_element = board[count][column_index]
        new_list.append(new_element)
    string_new_list = ''.join(new_list)
    return string_new_list
Run Code Online (Sandbox Code Playgroud)

还有一种更pythonic的方式来写这个

Mar*_*ers 5

您已经在board使用循环访问每个元素:

for i in board:
Run Code Online (Sandbox Code Playgroud)

i必将对中的每个元素board序列,你没有需要在这里使用一个单独的计数器。以下工作正常:

for i in board:
    new_element = i[column_index]
    new_list.append(new_element)
Run Code Online (Sandbox Code Playgroud)

或者只是使用列表理解:

new_list = [row[column_index] for row in board]
Run Code Online (Sandbox Code Playgroud)

这意味着您的功能可以简化为:

def make_str_from_column(board, column_index):
    return ''.join([row[column_index] for row in board])
Run Code Online (Sandbox Code Playgroud)

Python 列表从 开始编制索引0,并且在编制索引count之前递增。如果count从那开始0意味着您使用board[1], thenboard[2]等,但最终会len(board)作为最后一个索引。没有这样的索引,len(board) - 1取而代之的是最后一个索引。