Python 字符串列表的拆分列表
我有一个包含多个字符串的列表,希望有一个字符串列表 我尝试: 我的输出: 良好的输出: 那怎么办Python 字符串列表的拆分列表,python,string,list,Python,String,List,我有一个包含多个字符串的列表,希望有一个字符串列表 我尝试: 我的输出: 良好的输出: 那怎么办 >>> [phrase.split() for phrase in phrases] [['hello', 'how', 'are', 'you'], ['the', 'book', 'is', 'good'], ['this', 'is', 'amazing'], ['i', 'am', 'angry']] 这将有助于: list_of_list = [words.split(
>>> [phrase.split() for phrase in phrases]
[['hello', 'how', 'are', 'you'], ['the', 'book', 'is', 'good'], ['this', 'is', 'amazing'], ['i', 'am', 'angry']]
这将有助于:
list_of_list = [words.split() for words in phrases]
其他选项,同时删除标点符号,以防万一:
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']]
另一种方法是将map与str.split一起使用: 输出:
[['hello', 'how', 'are', 'you'], ['the', 'book', 'is', 'good'], ['this', 'is', 'amazing'], ['i', 'am', 'angry']]
list_of_list = [words.split() for words in phrases]
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']]
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']]