python - Splitting lists within a 2d list -
say have 2d list called sentences
.
sentences = [['hello'],['my'],['name']].
is there anyway split these lists every character separate indexes, like:
sentences = [['h','e','l','l','o'],['m','y'],['n','a','m','e']
for example: sentences.txt =
hello name
the code i've written:
sentence = open('sentences.txt', 'r') sentence_list = [] new_sentence_list = [] line in sentence: line = line.rstrip('\n') sentence_list.append(line) line in sentence_list: line = [line] new_sentence_list.append(line)
this result in new_sentence_list
be:
[['hello'],['my'], ['name']].
when be:
[['h','e','l','l','o'],['m','y'],['n','a','m','e']
you need use list(line)
achieve this:
so, code becomes below, original line commented.
sentence = open('sentences.txt', 'r') sentence_list = [] new_sentence_list = [] line in sentence: line = line.rstrip('\n') sentence_list.append(line) line in sentence_list: line = list(line) # line = [line] new_sentence_list.append(line)
Comments
Post a Comment