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

2024-10-01 17:30:47 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例如:

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)]

会给我一些像:

^{pr2}$

我不知道如何使用字符串拆分使我的输出如下所示:

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

有没有办法让我做这个?在


Tags: 字符串name列表defmoreaswithsome
3条回答

你可以这样高效地实现你想要的:

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

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

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]

输出:[['these', 'are', 'some', 'words'], ['these', 'are', 'some', 'more', 'words'], ['these', 'are', 'even', 'more', 'words'], ['these', 'are', 'the', 'last', 'words']]

简单的list comprehension可以帮你完成。在

如果,比如说

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

那么

^{pr2}$

会给你

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

而不是产生contentLists,也就是x,然后从中y,不是吗?在

相关问题 更多 >

    热门问题