【问题标题】:How to split strings inside a list by whitespace characters如何通过空格字符拆分列表中的字符串
【发布时间】:2017-10-20 12:04:09
【问题描述】:

所以stdin将一串文本返回到一个列表中,多行文本都是列表元素。 您如何将它们全部拆分为单个单词?

mylist = ['this is a string of text \n', 'this is a different string of text \n', 'and for good measure here is another one \n']

想要的输出:

newlist = ['this', 'is', 'a', 'string', 'of', 'text', 'this', 'is', 'a', 'different', 'string', 'of', 'text', 'and', 'for', 'good', 'measure', 'here', 'is', 'another', 'one']

【问题讨论】:

标签: python string list split


【解决方案1】:

您可以使用简单的列表推导,例如:

newlist = [<b>word</b> for line in mylist <b>for word in line.split()</b>]

这会生成:

>>> [word for line in mylist for word in line.split()]
['this', 'is', 'a', 'string', 'of', 'text', 'this', 'is', 'a', 'different', 'string', 'of', 'text', 'and', 'for', 'good', 'measure', 'here', 'is', 'another', 'one']

【讨论】:

    【解决方案2】:

    你可以这样做:

    words = str(list).split()
    

    因此,您将列表转换为字符串,然后用空格键将其拆分。 然后,您可以通过以下方式删除 /n:

    words.replace("/n", "")
    

    或者如果你想在一行中完成:

    words = str(str(str(list).split()).replace("/n", "")).split()
    

    只是说这在 python 2 中可能行不通

    【讨论】:

      【解决方案3】:

      除了我保证的上述列表理解答案之外,您还可以在 for 循环中进行:

      #Define the newlist as an empty list
      newlist = list()
      #Iterate over mylist items
      for item in mylist:
       #split the element string into a list of words
       itemWords = item.split()
       #extend newlist to include all itemWords
       newlist.extend(itemWords)
      print(newlist)
      

      最终您的newlist 将包含mylist 中所有元素中的所有拆分词

      但是 python 列表推导看起来要好得多,你可以用它做一些很棒的事情。在这里查看更多信息:

      https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

      【讨论】:

      • 是的,感谢您让我参与其中,我整个周末都在研究它。这是解决问题的好方法。我主要关心的是速度和效率,在我看来,作为内置 python 语言的一部分的列表推导比循环更快。
      【解决方案4】:

      或者,您可以使用mapstr.split 方法对列表中的每个字符串,然后通过itertools.chain.from_iterable 将结果列表中的元素链接在一起:

      from itertools import chain
      
      mylist = ['this is a string of text \n', 'this is a different string of text \n', 'and for good measure here is another one \n']
      result = list(chain.from_iterable(map(str.split, mylist)))
      print(result)
      # ['this', 'is', 'a', 'string', 'of', 'text', 'this', 'is', 'a', 'different', 'string', 'of', 'text', 'and', 'for', 'good', 'measure', 'here', 'is', 'another', 'one']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-03
        • 2017-06-01
        • 2018-05-16
        • 2016-04-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多