假设我有一个名为sentences
的2D列表。
sentences = [['hello'],['my'],['name']].
无论如何将每个字符的这些列表拆分成单独的索引,所以它看起来像:
sentences = [['h','e','l','l','o'],['m','y'],['n','a','m','e']
例如: sentences.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']
答案 0 :(得分:2)
列表理解非常简单:
new_sentences = [list(sentence[0]) for sentence in sentences]
申请
sentences = [['hello'],['my'],['name']]
产量
[['h', 'e', 'l', 'l', 'o'], ['m', 'y'], ['n', 'a', 'm', 'e']]
答案 1 :(得分:0)
您只需使用seti-ui
即可实现此目的:
因此,您的代码将在下方,您的原始行已被评论。
list(line)