Let say I have this list:
list1 = ["I", "am", "happy", " ", "and", "fine", " ", "and", "good"]
I want to end up with:
sublist1 = ["I", "am", "happy"]
sublist2 = ["and", "fine"]
sublist3 = ["and", "good"]
So, I want to split the list into sub-lists based on the space that in there in list1
.
Given a list of lists and list of length, the task is to split the list into sublists of given length. Method #1: Using islice to split a list into sublists of given length, is the most elegant way. # into sublists of given length. Method #2: Using zip is another way to split a list into sublists of given length.
The split() method of the string class is fairly straightforward. It splits the string, given a delimiter, and returns a list consisting of the elements split out from the string. By default, the delimiter is set to a whitespace - so if you omit the delimiter argument, your string will be split on each whitespace.
itertools.groupby
is the perfect weapon for this, using the str.isspace
property to separate the groups, and filtering out the groups with space.
import itertools
list1 = ["I", "am", "happy", " ", "and", "fine", " ", "and", "good"]
result = [list(v) for k,v in itertools.groupby(list1,key=str.isspace) if not k]
print(result)
result:
[['I', 'am', 'happy'], ['and', 'fine'], ['and', 'good']]
if you know there are 3 variables (which is not very wise) you could unpack
sublist1,sublist2,sublist3 = result
but it's better to keep the result as a list of lists.
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