我在列表中有三个句子:
sentences = []
sentence.append("This is my first sentence.")
sentence.append("This is my second sentence.")
sentence.append("This is my third sentence.")
我需要拆分它们,所以结果应该是: [['This','is','my','first','sentence。'], ['This','is','my','second','sentence。'], ['这','是','我','第三','句子。']]
我尝试按照以下方式分配一个新列表:
sentencesplit = []
for i in range(0, 3):
sentencesplit.extend(sentence[i].split())
结果是包含句子中所有分割字符串的一维列表。我甚至试图宣布
sentencesplit[[]]
for i in range(0, 3):
sentencesplit[i].extend(sentence[i].split())
但这只会导致错误消息列表索引超出范围。
知道如何解决这个问题吗?
答案 0 :(得分:3)
[sentence.split(' ') for sentence in sentences]
答案 1 :(得分:0)
尝试使用“追加”:
sentencesplit = []
for i in range(0, 3):
sentencesplit.append(sentence[i].split())
答案 2 :(得分:0)
sentenceList = ["This is my first sentence.",
"This is my second sentence.",
"This is my third sentence."]
result = []
for i in range(len(sentenceList)):
result.append(sentenceList[i].split(" "))
打印结果
[['This', 'is', 'my', 'first', 'sentence.'],
['This', 'is', 'my', 'second', 'sentence.'],
['This', 'is', 'my', 'third', 'sentence.']]
答案 3 :(得分:0)
只需使用简单的map
和lambda
来制作列表:
>>> strs = ['This is an example','This is an example','This is an example']
>>> map(lambda split_str: split_str.split(' '), strs)
[['This', 'is', 'an', 'example'], ['This', 'is', 'an', 'example'], ['This', 'is', 'an', 'example']]
或没有lamdba
:
>>> import string
>>> strs = ['This is an example','This is an example','This is an example']
>>> map(string.split, strs)
[['This', 'is', 'an', 'example'], ['This', 'is', 'an', 'example'], ['This', 'is', 'an', 'example']]
答案 4 :(得分:0)
sentences = []
sentences.append("This is my first sentence.".split())
sentences.append("This is my second sentence.".split())
sentences.append("This is my third sentence.".split())
在追加之前拆分它们。