如何在Python中拆分嵌套列表中的字符串?

如何在Python中拆分嵌套列表中的字符串?,python,string,list,nested-lists,string-split,Python,String,List,Nested Lists,String Split,我知道如何使用这些字符串将字符串列表拆分为嵌套列表,但我不确定现在如何将这些字符串拆分为多个字符串 例如: def inputSplit(file_name): with open(file_name) as f: content = f.read().splitlines() i = 0 contentLists = [content[i:i+1] for i in range(0, len(content), 1)] 给我一些类似的信息: [['th

我知道如何使用这些字符串将字符串列表拆分为嵌套列表,但我不确定现在如何将这些字符串拆分为多个字符串

例如:

def inputSplit(file_name):
    with open(file_name) as f:
        content = f.read().splitlines()
    i = 0
    contentLists = [content[i:i+1] for i in range(0, len(content), 1)]
给我一些类似的信息:

[['these are some words'], ['these are some more words'], ['these are even more words'], ['these are the last words']]
我不确定如何使用字符串拆分使我的输出如下所示:

[['these', 'are', 'some', 'words'], ['these', 'are', 'some', 'more', 'words'], ['these', 'are', 'even', 'more', 'words'], ['these', 'are', 'the', 'last', 'words']]
有什么办法可以帮你吗

x=[['these are some words'], ['these are some more words'], ['these are even more words'], ['these are the last words']]
print [i[0].split() for i in x]
输出:
[[“这些”、“是”、“一些”、“单词”]、[“这些”、“是”、“一些”、“更多”、“单词”]、[“这些”、“是”、“甚至”、“更多”、“单词”]、[“这些”、“是”、“最后一个”、“单词”]

简单的
列表理解
可以帮你做到。

如果

x = [['these are some words'], ['these are some more words'], ['these are even more words'], ['these are the last words']]
然后

我会给你

[['these', 'are', 'some', 'words'], ['these', 'are', 'some', 'more', 'words'], ['these', 'are', 'even', 'more', 'words'], ['these', 'are', 'the', 'last', 'words']]
如所愿

但是,如果你原来的表情

contentLists = [content[i:i+1] for i in range(0, len(content), 1)]
生成我在这里称为
x
的列表,这是毫无意义的——为什么首先要创建一个长度为1的子列表

看起来像是您想要的,直接:

y = [item.split() for item in content]

与其生成
内容列表
,又称
x
,然后从中生成
y
,不?

您可以通过以下高效方式实现您想要的:

with open(file_path) as input_file:
    content_lists = [line.split() for line in input_file]

事实上,
f.read()
首先将整个文件加载到内存中,然后
.splitlines()
创建一个分为几行的副本:不需要这两个数据结构,因为您可以简单地逐行读取文件,然后依次拆分每一行,如上所述。这更有效、更简单。

旁注:
content=f。readlines()
将更简单、更有效。不过,还有一个更简单、更有效的解决方案(例如,请参见我的答案)。
with open(file_path) as input_file:
    content_lists = [line.split() for line in input_file]