如何用空格字符在列表中拆分字符串
发布于 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 个回答
-
您可以使用简单的列表推导,例如:
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']