Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a list into other sublists, splitting will be based on a space defined in the main list [duplicate]

Tags:

python

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.

like image 424
Dee.Es Avatar asked Sep 16 '17 09:09

Dee.Es


People also ask

How do I split a list into N Sublists?

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.

How do you split data in a list?

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.


1 Answers

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.

like image 110
Jean-François Fabre Avatar answered Oct 27 '22 00:10

Jean-François Fabre