Split strings in a list of lists

China☆狼群 提交于 2020-05-28 07:26:06

问题


I currently have a list of lists:

[['Hi my name is'],['What are you doing today'],['Would love some help']]

And I would like to split the strings in the lists, while remaining in their current location. For example

[['Hi','my','name','is']...].. 

How can I do this?

Also, if I would like to use a specific of the lists after searching for it, say I search for "Doing", and then want to append something to that specific list.. how would I go about doing that?


回答1:


You can use a list comprehension to create new list of lists with all the sentences split:

[lst[0].split() for lst in list_of_lists]

Now you can loop through this and find the list matching a condition:

for sublist in list_of_lists:
    if 'doing' in sublist:
        sublist.append('something')

or searching case insensitively, use any() and a generator expression; this will the minimum number of words to find a match:

for sublist in list_of_lists:
    if any(w.lower() == 'doing' for w in sublist):
        sublist.append('something')



回答2:


list1 = [['Hi my name is'],['What are you doing today'],['Would love some help']]

use

[i[0].split() for i in list1]

then you will get the output like

[['Hi', 'my', 'name', 'is'], ['What', 'are', 'you', 'doing', 'today'], ['Would', 'love', 'some', 'help']]



回答3:


l = [['Hi my name is'],['What are you doing today'],['Would love some help']]

for x in l:
    l[l.index(x)] = x[0].split(' ')

print l

Or simply:

l = [x[0].split(' ') for x in l]

Output

[['Hi', 'my', 'name', 'is'], ['What', 'are', 'you', 'doing', 'today'], ['Would', 'love', 'some', 'help']]


来源:https://stackoverflow.com/questions/19927859/split-strings-in-a-list-of-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!