gpt4 book ai didi

python - 海峡列表列表

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

我正在尝试编写一个函数,它将在 shell 中打开一个 .txt 文件作为 str 列表的列表。

文件是这样的:

TYUIO
GHJKL
BNMCV
ASDFG
XCVBN

我需要我的函数返回:

[['T', 'Y', 'U', 'I', 'O'], ['G', 'H', 'J', 'K', 'L'], ...]

等等。

我写的函数几乎产生了这个。它返回:

[['TYUIO'], ['GHJKL'], ...]

等等。我需要对此函数进行更改/添加什么以使其返回正确的嵌套列表?

这是我的功能:

board_list = []
for line in board_file:
items = line.rstrip('\n').split('\t')
items = [item.strip() for item in items]
board_list.append(items)

return board_list

有人能帮忙吗?

最佳答案

尝试使用 list()extend()

items = [list(item.strip()) for item in items]
board_list.extend(items)

你也可以在一行中完成,假设每一行包含一个单词。我不确定你为什么要在 \t 上拆分,所以这可能不适合你。

with open("data.txt") as board_file:
board_list = [list(line) for line in board_file.read().split('\n') if line]

关于python - 海峡列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13331895/

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