gpt4 book ai didi

python - 在二维列表中拆分列表

转载 作者:行者123 更新时间:2023-11-30 22:32:45 24 4
gpt4 key购买 nike

假设我有一个名为 sentences 的 2D 列表。

sentences = [['hello'],['my'],['name']].  

是否有办法将这些列表中的每个字符拆分为单独的索引,因此它看起来像:

sentences = [['h','e','l','l','o'],['m','y'],['n','a','m','e']

例如: 句子.txt =

hello
my
name

我写的代码:

sentence = open('sentences.txt', 'r')
sentence_list = []
new_sentence_list = []
for line in sentence:
line = line.rstrip('\n')
sentence_list.append(line)
for line in sentence_list:
line = [line]
new_sentence_list.append(line)

这将导致 new_sentence_list 为:

[['hello'],['my'], ['name']].  

当我希望它是:

[['h','e','l','l','o'],['m','y'],['n','a','m','e']

最佳答案

非常简单的列表理解:

new_sentences = [list(sentence[0]) for sentence in sentences]

适用于

sentences = [['hello'],['my'],['name']]

产量

[['h', 'e', 'l', 'l', 'o'], ['m', 'y'], ['n', 'a', 'm', 'e']]

关于python - 在二维列表中拆分列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45364712/

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