简体   繁体   English

将列表添加到新列表

[英]Adding lists to a new list

I did not get this question right. 我没有正确回答这个问题。 The function read_words turns a text file with a bunch of names in new lines into a list and it works. 函数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

the problem arises when I try to get a list of lists 当我尝试获取列表列表时出现问题

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

the goal is to turn a text file of the type: 目标是打开以下类型的文本文件:

ABCD
EFGH

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

I have already tried playing around with the indices for board_list.append(row_list) call without luck. 我已经尝试过用board_list.append(row_list)调用的索引来运气了。 How can I get this to work? 我该如何工作?

You can do that with a list comprehension and .strip() like: 您可以使用列表 .strip().strip()来做到这一点,例如:

Code: 码:

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

Test Code: 测试代码:

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)

Results: 结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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