简体   繁体   中英

Splitting a list of n words into n lists of single words

I have got a list of sublists with potentially multiple words:

l = [['word1'], ['word2'], ['word1'], ['word1', 'word3'], ['word4']]

I want to get a list of sublists where each sublist is constituted of only one word such that:

l = [['word1'], ['word2'], ['word1'], ['word1'], ['word3'], ['word4']]

I wrote:

for i in l:
    if len(i) > 1 : 
        [l.append([j]) for j in i]
        l.remove(i)

print(l)

It appears to work (even if the words of the splitted sublist go at the end of the list), but the list comprehension prints:

[None, None]

What is the reason for this? Is there a better way of doing?

A nested list comprehension will do that in one line:

[ [word] for wlist in l for word in wlist ]

[['word1'], ['word2'], ['word1'], ['word1'], ['word3'], ['word4']]

I think this will work

for i in l:
    if len(i) > 1 :
        for j in i:
            l.append([j]) 
        l.remove(i)

print(l)

Similar to your approach for nested and multi level nested lists. Unfortunately, this solution breaks when the first element of a nested list is a list.

l = [['word1','word2'],
     ['word3'],
     ['word4'],
     ['word5', ['word6','word7',['word8','word9'],'word10']],
     ['word11','word12'],
     ['word13'],
     ['word14', 'word15', 'word16'],
     ['word17']]

for i in l:
    if len(i) > 1:
        idx = l.index(i)
        l[idx:idx+1] = [w if isinstance(w, list) else [w] for w in i]

print(l)

Output

[['word1'],
 ['word2'],
 ['word3'],
 ['word4'],
 ['word5'],
 ['word6'],
 ['word7'],
 ['word8'],
 ['word9'],
 ['word10'],
 ['word11'],
 ['word12'],
 ['word13'],
 ['word14'],
 ['word15'],
 ['word16'],
 ['word17']]

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