Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在二维列表中拆分列表_Python_Python 3.6 - Fatal编程技术网

Python 在二维列表中拆分列表

Python 在二维列表中拆分列表,python,python-3.6,Python,Python 3.6,假设我有一个名为句子的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 = []

假设我有一个名为
句子的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)
这将导致新句子列表
为:

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

您只需使用
list(line)
即可实现此目的:

因此,您的代码将显示在下面,您的原始行将被注释

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 = list(line)
    # line = [line]
    new_sentence_list.append(line)

如果你做了
list('hello')
你会得到
['h','e','l','l','o']
@idjaw你应该把它作为一个答案,这正是OP需要的。完美!谢谢