如何通过空格字符在列表中拆分字符串 [英] How to split strings inside a list by whitespace characters
本文介绍了如何通过空格字符在列表中拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,stdin将一串文本返回到列表中,并且多行文本都是列表元素. 您如何将它们全部分割成一个单词?
So stdin returns a string of text into a list, and multiple lines of text are all list elements. How do you split them all into single words?
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']
推荐答案
您可以使用简单的列表理解,例如:
You can use simple list comprehension, like:
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']
这篇关于如何通过空格字符在列表中拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文