向新lis添加列表

2024-04-26 23:01:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我没有答对这个问题。函数read_words将新行中包含一堆名称的文本文件转换为一个列表,然后就可以工作了。你知道吗

def read_words(words_file):
    """ (file open for reading) -> list of str
    Return a list of all words (with newlines removed) from open file
    words_file.
    Precondition: Each line of the file contains a word in uppercase characters
    from the standard English alphabet.
    """
    words_list = []
    words = words_file.readlines()
    for i in range(len(words)):
        new_word = words[i]
        for char in '\n':
            new_word = new_word.replace(char,'')
            words_list.append(new_word)
    return words_list

当我尝试获取列表列表时,问题就出现了

def read_board(board_file):
    """ (file open for reading) -> list of list of str
    Return a board read from open file board_file. The board file will contain
    one row of the board per line. Newlines are not included in the board.
    """
    board_list = []
    row_list = []
    rows = read_words(board_file)
    for i in range(len(rows)):
        for  char in rows[i]:
            row_list.append(char)
        board_list.append(row_list)
    return board_list

目标是打开以下类型的文本文件:

ABCD
EFGH

变成[['A','B','C','D'],['E','F','G','H']]

我已经尝试过不走运地使用board_list.append(row_list)调用的索引。我怎样才能让它工作?你知道吗


Tags: oftheinboardnewforreadopen
1条回答
网友
1楼 · 发布于 2024-04-26 23:01:59

你可以用list comprehension^{}这样做:

代码:

def read_board(board_file):
    return [list(line.strip()) for line in read_words(board_file)]

测试代码:

def read_words(words_file):
    """ (file open for reading) -> list of str
    Return a list of all words (with newlines removed) from open file
    words_file.
    Precondition: Each line of the file contains a word in uppercase characters
    from the standard English alphabet.
    """
    return [word.strip() for word in words_file.readlines()]

def read_board(board_file):
    """ (file open for reading) -> list of list of str
    Return a board read from open file board_file. The board file will contain
    one row of the board per line. Newlines are not included in the board.
    """
    return [list(line) for line in read_words(board_file)]

with open('file1', 'rU') as f:
    board = read_board(f)

print(board)

结果:

[['A', 'B', 'C', 'D'], ['E', 'F', 'G', 'H']]

相关问题 更多 >