Python 我想将字符串列表拆分为二维数组

Python 我想将字符串列表拆分为二维数组,python,Python,我的清单上有三句话: sentences = [] sentence.append("This is my first sentence.") sentence.append("This is my second sentence.") sentence.append("This is my third sentence.") 我需要拆分它们,因此结果应该是: 这是我的第一句话, [“这”、“是”、“我的”、“第二个”、“句子”。], [“这”、“是”、“我的”、“第三个”、“句子”。]] 我

我的清单上有三句话:

sentences = []
sentence.append("This is my first sentence.")
sentence.append("This is my second sentence.")
sentence.append("This is my third 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())
但这只会导致错误消息列表索引超出范围

知道如何解决这个问题吗?

尝试使用append:

sentencesplit = []
for i in range(0, 3):
   sentencesplit.append(sentence[i].split())
尝试使用append:

sentencesplit = []
for i in range(0, 3):
   sentencesplit.append(sentence[i].split())
打印结果

打印结果

只需使用simple 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:

只需使用simple 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:

在追加之前先拆分它们


在追加之前拆分它们。

您可以在追加自身时拆分它们。这是我的第一句话。你为什么用extend?有很多有用的答案,但如果你只将extend改为append,它会按照你的要求工作。你可以在追加时拆分它们。这是我的第一句话。你为什么用extend?有很多有用的答案,但是如果你只将extend改为append,它会按照你的要求工作。+1对于列表理解,简单易读的一行。我本来会保留“”的,因为它是标准拆分,但是。。。PythonZen说,对于简单易读的一行代码,可以显式地使用:+1。我本来会保留“”的,因为它是标准拆分,但是。。。Python Zen说,直截了当是可以的:哈,比我快。我正要创建一个较短的版本+1>>编辑:看起来我们有一个连续的投票人…哈,快来吧。我正要创建一个较短的版本+1>>编辑:看起来我们有一个串行下行表决器。。。
>>> 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']]
[sentence.split(' ')  for sentence in sentences]
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())