Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a list into sublists based on a separator, similar to str.split()?

Tags:

python

Given a list like:

[a, SEP, b, c, SEP, SEP, d]

how do I split it into a list of sublists:

[[a], [b, c], [], [d]]

Effectively I need an equivalent of str.split() for lists. I can hack together something, but I can't seem to be able to come up with anything neat and/or pythonic.

I get the input from an iterator, so a generator working on that is acceptable as well.

More examples:

[a, SEP, SEP, SEP] -> [[a], [], [], []]

[a, b, c] -> [[a, b, c]]

[SEP] -> [[], []]
like image 612
Jani Avatar asked Jan 25 '19 20:01

Jani


People also ask

How do you split a list into two sublists in Python?

Split List Into Sublists Using the array_split() Function in NumPy. The array_split() method in the NumPy library can also split a large array into multiple small arrays. This function takes the original array and the number of chunks we need to split the array into and returns the split chunks.

How do you split data in a list?

Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do you split apart a list in Python?

To split a list into n parts in Python, use the numpy. array_split() function. The np. split() function splits the array into multiple sub-arrays.

Can you use the split function with a list?

A split function can be used to split strings with the help of a delimiter. A split function can be used to split strings with the help of the occurrence of a character. A split function can be used to split strings in the form of a list.


2 Answers

A simple generator will work for all of the cases in your question:

def split(sequence, sep):
    chunk = []
    for val in sequence:
        if val == sep:
            yield chunk
            chunk = []
        else:
            chunk.append(val)
    yield chunk
like image 63
wim Avatar answered Nov 07 '22 23:11

wim


My first ever Python program :)

from pprint import pprint
my_array = ["a", "SEP", "SEP", "SEP"]
my_temp = []
my_final = []
for item in my_array:
  if item != "SEP":
    my_temp.append(item)
  else:
    my_final.append(my_temp);
    my_temp = []
pprint(my_final);
like image 24
Matthew Page Avatar answered Nov 07 '22 23:11

Matthew Page