简体   繁体   中英

Split strings in a list of lists

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?

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

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