如何将短语列表转换为单词列表?

时间:2019-07-30 09:41:09

标签: python python-3.x list

我想将同时包含短语和单词的列表转换为仅包含单词的列表。例如,如果输入为:

list_of_phrases_and_words = ['I am', 'John', 'michael and', 'I am', '16', 
    'years', 'old']

预期输出为:

list_of_words = ['I', 'am', 'John', 'michael', 'and', 'I', 'am', '16', 'years', 'old']

在Python中实现此目标的有效方法是什么?

2 个答案:

答案 0 :(得分:1)

您可以使用列表理解:

list_of_words = [
    word
    for phrase in list_of_phrases_and_words
    for word in phrase.split()
]

对于较大的列表,效率可能稍低的替代方法是先创建一个包含所有内容的大字符串,然后将其拆分:

list_of_words = " ".join(list_of_phrases_and_words).split()

答案 1 :(得分:0)

诀窍是嵌套的for循环,您可以在其中分割空格字符“”。

words = [word for phrase in list_of_phrases_and_words for word in phrase.split(" ")]