Crusader
Crusader

Reputation: 333

Convert given list to nested list - Python3.x

I have a list in the below format :

input = [['Monday', 'Tuesday', 'Wednesday', '', '1', '2', 'Black', '']]

I would like to convert this to a nested list like below : (See, nested list breaks at null element)

output = [['Monday', 'Tuesday', 'Wednesday'], ['1', '2', 'Black']]

Is there a way to do this? I tried hard to think but could not come up with a solution.

More Examples :

input = [['', 'word1', 'word2', '', '1', '2', 'orange', '']]
output = [['word1', 'word2'],['1', '2', 'orange']]
input = [['', '', 'word1', 'word2', '', '1', '2', 'word3', '', '']]
output = [['word1', 'word2'],['1', '2', 'word3']]

Thanks in advance!!!

Upvotes: 0

Views: 37

Answers (2)

Bharel
Bharel

Reputation: 26901

That should work:

import itertools
input_ = [['Monday', 'Tuesday', 'Wednesday', '', '1', '2', 'Black', '']]
output = [list(g) for item in input_ for k, g in itertools.groupby(item, bool) if k]

Longer solution:

input_ = [['Monday', 'Tuesday', 'Wednesday', '', '1', '2', 'Black', '']]
output = []
sublist = []
for item in input_:
    for subitem in item:
        if subitem:
            sublist.append(subitem)
            continue
        if sublist:
            output.append(sublist)
            sublist = []

Upvotes: 1

Sebastien D
Sebastien D

Reputation: 4482

Here is a way to do it:

x = [['', '', 'word1', 'word2', '', '1', '2', 'word3', '', '']]
output = []
temp = []
for idx, el in enumerate(x[0]):
    if idx == 0 and el == "":
        continue
    if el != '':
        temp.append(el)
    elif temp != []:
        output.append(temp)
        temp = []

Output

[['word1', 'word2'], ['1', '2', 'word3']]

Upvotes: 1

Related Questions