1

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

4
  • If you're splitting on '~', shouldn't the list start and end with an empty list []? Should empty lists not be included in the result? Commented Oct 22, 2018 at 18:55
  • no empty lists in the result, just simply what I said in the output Commented Oct 22, 2018 at 18:57
  • Related: Python spliting a list based on a delimiter word (Similar question, but includes the separator elements in the output) Commented Oct 22, 2018 at 19:05
  • @Aran-Fey this answer answers perfectly, that said: stackoverflow.com/a/15358422/6451573, in the first part (even if it's not the output that OP needs) Commented Oct 22, 2018 at 20:52

1 Answer 1

5

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]
Sign up to request clarification or add additional context in comments.

1 Comment

Ok great, follow up question. What if the '~'s were instead empty strings ''

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.