在2d列表中拆分列表

时间:2017-07-28 04:07:44

标签: python python-3.6

假设我有一个名为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']

2 个答案:

答案 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)