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] -> [[], []]
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.
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.
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.
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.
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With