如何用空格字符在列表中拆分字符串

发布于 2021-01-29 19:00:15

因此,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']
关注者
0
被浏览
446
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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

    newlist = [ **word** for line in mylist **for word in line.split()** ]
    

    这将产生:

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看