bbd108
bbd108

Reputation: 998

Split in a list by specific element to get a list of lists Python

Input

['~', 'n1', 'n2', ..., 'nn', '~', 'k1', 'k2', ..., 'kn', '~']

Desired output:

[['n1', 'n2', ..., 'nn'],['k1', 'k2', ..., 'kn']]

I have seen itertools groupby but cannot get it to work. Any help would be appreciated. Also the ... is not actually in the list, just saying there are more elements in between

Upvotes: 1

Views: 53

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140158

The groupby method is the best one.

group using the key function item != '~', and filter on the key being True (when x=='~', the key function returns False, the if k condition filters that out)

import itertools

lst = ['~', 'n1', 'n2', 'nn', '~', 'k1', 'k2', 'kn', '~']

result = [list(v) for k,v in itertools.groupby(lst,lambda x : x!='~') if k]

result:

[['n1', 'n2', 'nn'], ['k1', 'k2', 'kn']]

note that you have to force iteration on issued groups, since groupby returns iterables (just in case you just need to iterate on them again)

If you have empty strings, it's even simpler: no need for lambda, rely on the truthfullness of the values and use bool operator:

lst = ['', 'n1', 'n2', 'nn', '', 'k1', 'k2', 'kn', '']

result = [list(v) for k,v in itertools.groupby(lst,bool) if k]

Upvotes: 5

Related Questions