【问题标题】:Splitting strings inside of list in Python [duplicate]在Python中的列表内拆分字符串[重复]
【发布时间】:2020-12-30 02:47:46
【问题描述】:

虽然我遇到过似乎可以回答这个问题的帖子,但我从他们那里尝试过的任何东西都没有奏效。

我想做的就是把这样的列表转成这样:

["this is an\nexample" , "sentence\n\x0c"]

到这里:

["this", "is", "an", "example", "sentence"]

我敢肯定我把这个问题复杂化了,通常在论坛上搜索类似的问题是可行的,但由于某种原因,我遇到的任何问题都不是解决方案。

【问题讨论】:

    标签: python python-3.x string list split


    【解决方案1】:

    只需执行此操作(map 返回您的迭代器,您可以直接将其与空列表相加以一次性返回所需的输出):

    a = ["this is an\nexample" , "sentence\n\x0c"]
    a = sum(map(str.split, a), [])
    

    给予

    ['this', 'is', 'an', 'example', 'sentence']
    

    【讨论】:

    • 你怎么也申请.lower() cuz' 我得到一个AttributeError: 'method_descriptor' object has no attribute 'lower'
    【解决方案2】:

    你可以试试这个代码。 完全内置itertools,还有很多其他功能可能对你有用。

    from itertools import chain
    
    s = ["this is an\nexample" , "sentence\n\x0c"]
    
    
    s = [i.split() for i in s]
    
    print(list(chain(*s)))
    

    这样让它更短。但我认为第一个更好,因为它更眼睛友好

    from itertools import chain
    
    s = ["this is an\nexample" , "sentence\n\x0c"]
    print(list(chain(*[i.split() for i in s])))
    

    输出:

    ['this', 'is', 'an', 'example', 'sentence']
    

    【讨论】:

      【解决方案3】:

      应该像使用字符串的拆分方法一样简单。

      l = ["this is an\nexample" , "sentence\n\x0c"]
      l2 = []
      
      for i in l:
          l2 += (i.split())
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-07-13
        • 1970-01-01
        • 2012-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-27
        相关资源
        最近更新 更多