Extract Each Word From List Of Strings
I am using Python my list is str = ['Hello dude', 'What is your name', 'My name is Chetan'] I want to separate each word in each sentence in the string and store it in new_list. n
Solution 1:
You could use itertools.chain
from itertools import chain
def split_list_of_words(list_):
return list(chain.from_iterable(map(str.split, list_)))
DEMO
input_ = [
"Hello dude",
"What is your name",
"My name is Chetan"
]
result = split_list_of_words(input_)
print(result)
#['Hello', 'dude', 'What', 'is', 'your', 'name', 'My', 'name', 'is', 'Chetan']
Solution 2:
you have,
values = ["Hello dude", "What is your name", "My name is Chetan"]
then use this one liner
' '.join(values).split()
Solution 3:
This should help. Instead of append use extend
or +=
str = ["Hello dude", "What is your name", "My name is Chetan"]
new_list = []
for row in str:
new_list += row.split(" ") #or new_list.extend(row.split(" "))
print new_list
Output:
['Hello', 'dude', 'What', 'is', 'your', 'name', 'My', 'name', 'is', 'Chetan']
Solution 4:
new_list = [x for y in str for x in y.split(" ")]
Solution 5:
You are almost there. All that's left to do is to un-nest your list.
final_result = [x for sublist in new_list for x in sublist]
Or without a list comprehension:
final_result = []
for sublist in new_list:
for x in sublist:
final_result.append(x)
Of course, all of this can be done in a single step without producing new_list
first explicitly. The other answers already covered that.
Post a Comment for "Extract Each Word From List Of Strings"