简体   繁体   中英

Split list of list of strings

I have a list with several strings and would like to have a list of string lists

I try:

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] 

My output:

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

Good output:

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

What about

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

Other option, removing also punctuation, just in case:

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

Another way to do it is to use map with str.split :

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

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

print(splittedPhrases)

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM