[英]How to convert a list of phrases into list of words?
I want to convert a list which contains both phrases and words to a list which contains only words.我想将包含短语和单词的列表转换为仅包含单词的列表。 For example, if the input is:例如,如果输入是:
list_of_phrases_and_words = ['I am', 'John', 'michael and', 'I am', '16',
'years', 'old']
The expected output is:预期的输出是:
list_of_words = ['I', 'am', 'John', 'michael', 'and', 'I', 'am', '16', 'years', 'old']
What is the efficient way to achieve this is in Python?在 Python 中实现这一目标的有效方法是什么?
You can use a list comprehension:您可以使用列表理解:
list_of_words = [
word
for phrase in list_of_phrases_and_words
for word in phrase.split()
]
An alternative that might be slightly less efficient for larger lists would be to first create a large string containing everything and then splitting it:对于较大的列表,可能效率稍低的替代方法是首先创建一个包含所有内容的大字符串,然后将其拆分:
list_of_words = " ".join(list_of_phrases_and_words).split()
诀窍是一个嵌套的 for 循环,您可以在空格字符“”上进行拆分。
words = [word for phrase in list_of_phrases_and_words for word in phrase.split(" ")]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.