【问题标题】:How do I split strings within nested lists in Python?如何在 Python 的嵌套列表中拆分字符串?
【发布时间】:2015-05-14 03:42:30
【问题描述】:

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

例如:

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

有什么办法可以解决这个问题吗?

【问题讨论】:

  • 旁注:content = f.readlines() 会更简单、更高效。不过,还有一个更简单、更有效的解决方案(例如,请参阅我的答案)。

标签: python string list nested-lists string-split


【解决方案1】:

如果说,

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

然后

 y = [sublist[0].split() for sublist in x]

会给你

[['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,不是吗?

【讨论】:

    【解决方案2】:
    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可以帮你搞定。

    【讨论】:

      【解决方案3】:

      您可以像这样以一种有效的方式实现您想要的:

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

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

      【讨论】:

        猜你喜欢
        • 2014-04-26
        • 1970-01-01
        • 2023-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多