-1

I want to split or separate this list wherever there is an empty list []

Sample list:

lists = [['I'], ['speak'], ['english'], [], ['I'], ['speak'], ['spanish'], [], ['I'], ['speak'], ['Hindu']]

Desired output:

lists = [
[['I'], ['speak'],['english']],
[['I'], ['speak'],['spanish']],
[['I'], ['speak'],['Hindu']],
]

How do I achieve this?

I've tried:

new_list = []
for I in range(len(lists)):
    temp_list = []
    if lists[i] != []:
        temp_list.append(lists [i])
    new_list.append(temp_list)
Bruno
  • 655
  • 8
  • 18

3 Answers3

3

You can use itertools.groupby() to achieve this as:

from itertools import groupby
my_list = [['I'], ['speak'], ['english'], [], ['I'], ['speak'], ['spanish'], [], ['I'], ['speak'], ['Hindu']]

new_list = [list(l) for i, l in groupby(my_list, bool) if i]

where new_list holds:

[
    [['I'], ['speak'], ['english']], 
    [['I'], ['speak'], ['spanish']], 
    [['I'], ['speak'], ['Hindu']]
]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
-1
new_list = [[]]
for item in lists:
    if item:
       new_list[-1].append(item[0])
    else:
        new_list.append([])

result:

[['I', 'speak', 'english'], ['I', 'speak', 'spanish'], ['I', 'speak', 'Hindu']]
Semmel
  • 575
  • 2
  • 8
-1

as you can see a way to solve the problem is this , you can use a Method that includes :

Using list comprehension + zip() + slicing + enumerate()

where you first split list into lists by particular value

size = len(test_list) 
idx_list = [idx + 1 for idx, val in
            enumerate(test_list) if val == 5]

and then create a new one

res = [test_list[i: j] for i, j in
        zip([0] + idx_list, idx_list + 
        ([size] if idx_list[-1] != size else []))] 
Johan
  • 29
  • 5
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/28228974) – Muhammad Usman Feb 02 '21 at 18:16
  • 1
    Done, I just Edited to be more helpful @MuhammadUsman – Johan Feb 02 '21 at 18:34