ogcurious
ogcurious

Reputation: 11

Breaking up list into lists by splitting along specific item

Complete Python beginner here.

I have a list like this:

[Day1_item1, Day1_item2, Day1_item3, None, Day2_item1, Day2_item2, None, Day3_item1]

None here is basically empty space.

I want to create a list of lists out of this. It should look like this:

[[Day1_item1, Day1_item2, Day1_item3],[Day2_item1, Day2_item2],[Day3_item1]]

So far I tried this:

# Experiment 1
days = [day for day in all_items_list if day != None]

and this:

# Experiment 2
    days = []
for item in all_items_list:
  while True:
    item in all_items_list != None
    days.append(item[:])
    if item == None:
      break

Both don't give an error but don't produce the result I want. Experiment 1 just removes the 'None' and adds everything to a new list, Experiment 2 does not produce any result.

Any idea what I could do here?

Thanks in advance!

Upvotes: 0

Views: 58

Answers (2)

Alain T.
Alain T.

Reputation: 42143

From the indices of the None elements, you can use zip() to form subscripts and extract them from your list:

L = ["Day1_item1", "Day1_item2", "Day1_item3", None, "Day2_item1", 
     "Day2_item2", None, "Day3_item1"]

breaks = [ i for i,v in enumerate(L) if v is None ]
R      = [ L[s+1:e] for s,e in zip([-1]+breaks,breaks+[len(L)]) ]

print(R)
[['Day1_item1', 'Day1_item2', 'Day1_item3'], 
 ['Day2_item1', 'Day2_item2'], ['Day3_item1']]

Upvotes: 0

Vishal Singh
Vishal Singh

Reputation: 6234

You can write a simple for loop to make None act as a separator between list elements.

output = []
temp = []

for item in ll:
    if item is not None:
        temp.append(item)
    else:
        output.append(temp)
        temp = []

output.append(temp)  # handles the last item of the list

output = [item for item in output if item]  # removing empty lists

Output:

[['Day1_item1', 'Day1_item2', 'Day1_item3'], ['Day2_item1', 'Day2_item2'], ['Day3_item1']]

Upvotes: 1

Related Questions