拆分字符串列表

时间:2019-01-08 13:52:12

标签: python string list

我有一个包含多个字符串的列表,并且想要一个字符串列表的列表

我尝试:

phrases = ['hello how are you', 'the book is good', 'this is amazing', 'i am angry']

list_of_list = [words for phrase in phrases for words in phrase] 

我的输出:

['h', 'e', 'l', 'l', 'o', ' ', 'h', 'o', 'w', ' ', ...]

好的输出:

[['hello', 'how', 'are', 'you'], ['the', 'book', 'is', 'good'], ['this', 'is', 'amazing'], ['i', 'am', 'angry']

4 个答案:

答案 0 :(得分:3)

>>> [phrase.split() for phrase in phrases]
[['hello', 'how', 'are', 'you'], ['the', 'book', 'is', 'good'], ['this', 'is', 'amazing'], ['i', 'am', 'angry']]

答案 1 :(得分:3)

这可以做到:

list_of_list = [words.split() for words in phrases] 

答案 2 :(得分:1)

其他选项,也删除标点符号,以防万一:

import re

phrases = ['hello! how are you?', 'the book is good!', 'this is amazing!!', 'hey, i am angry']
list_of_list_of_words = [ re.findall(r'\w+', phrase) for phrase in phrases ]

print(list_of_list_of_words)
#=> [['hello', 'how', 'are', 'you'], ['the', 'book', 'is', 'good'], ['this', 'is', 'amazing'], ['hey', 'i', 'am', 'angry']]

答案 3 :(得分:1)

另一种方法是将mapstr.split一起使用:

phrases = ['hello how are you', 'the book is good', 'this is amazing', 'i am angry']

splittedPhrases = list(map(str.split,phrases))

print(splittedPhrases)

输出:

[['hello', 'how', 'are', 'you'], ['the', 'book', 'is', 'good'], ['this', 'is', 'amazing'], ['i', 'am', 'angry']]