如何通过空格字符拆分列表中的字符串

14

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

4个回答

23
您可以使用简单的列表推导式,例如:
newlist = [<b>word</b> for line in mylist <b>for word in line.split()</b>]
这将生成:
>>> [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']

6
你可以这样做:

你只需要执行以下操作:

words = str(list).split()

所以你需要将列表转换为字符串,然后通过空格进行分割。 接下来,你可以通过以下方式去掉/n:

words.replace("/n", "")

如果您想在一行代码中完成此操作:
words = str(str(str(list).split()).replace("/n", "")).split()

仅仅说这个可能不适用于Python 2。


3
除了上面的列表推导式答案,我为之担保,你还可以用for循环来完成:
#Define the newlist as an empty list
newlist = list()
#Iterate over mylist items
for item in mylist:
 #split the element string into a list of words
 itemWords = item.split()
 #extend newlist to include all itemWords
 newlist.extend(itemWords)
print(newlist)

最终你的newlist将包含所有在mylist中所有元素中出现的拆分单词。
但是python列表推导看起来更好,并且您可以使用它做很多很棒的事情。在此处查看更多详细信息:https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

是的,谢谢你让我知道这个,我整个周末都在研究它。这是一个不错而优雅的解决问题的方式。我的主要关注点是速度和效率,我认为列表推导式作为Python内置语言的一部分比循环更快。 - iFunction

2
或者,您可以对列表中的每个字符串使用str.split方法,然后通过itertools.chain.from_iterable将结果列表的元素链接在一起。同时,您还可以map地处理这些字符串。
from itertools import chain

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']
result = list(chain.from_iterable(map(str.split, mylist)))
print(result)
# ['this', 'is', 'a', 'string', 'of', 'text', 'this', 'is', 'a', 'different', 'string', 'of', 'text', 'and', 'for', 'good', 'measure', 'here', 'is', 'another', 'one']

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接