如何按空格字符拆分列表中的字符串 [英] How to split strings inside a list by whitespace characters

查看:55
本文介绍了如何按空格字符拆分列表中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以stdin将一串文本返回到一个列表中,多行文本都是列表元素.你如何将它们全部拆分成单个词?

mylist = ['this is a string of text 
', 'this is a different string of text 
', '这里是另一个
']

想要的输出:

newlist = ['this', 'is', 'a', 'string', 'of', 'text', 'this', 'is', 'a', '不同', '字符串', 'of', 'text', 'and', 'for', 'good', 'measure', 'here', 'is', 'another', 'one']

解决方案

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

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

这会产生:

<预><代码>>>>[mylist 中的行中的单词 line.split() 中的单词]['this', 'is', 'a', 'string', 'of', 'text', 'this', 'is', 'a', '不同', 'string', 'of', '文本', 'and', 'for', 'good', 'measure', 'here', 'is', 'another', 'one']

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 
', 'this is a different string of text 
', 'and for good measure here is another one 
']

wanted output:

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()]

This generates:

>>> [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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆