因此,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']
您可以使用简单的列表推导,例如:
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']
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句