gpt4 book ai didi

python - 将列表添加到新列表

转载 作者:太空宇宙 更新时间:2023-11-04 00:21:02 25 4
gpt4 key购买 nike

我没答对这个问题。函数 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) 调用的索引,但没有成功。我怎样才能让它发挥作用?

最佳答案

您可以使用 list comprehension 来做到这一点和 .strip()喜欢:

代码:

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

关于python - 将列表添加到新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49100930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com