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

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
bbd108
  • 958
  • 2
  • 10
  • 26
  • 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? – Aran-Fey Oct 22 '18 at 18:55
  • no empty lists in the result, just simply what I said in the output – bbd108 Oct 22 '18 at 18:57
  • Related: [Python spliting a list based on a delimiter word](//stackoverflow.com/q/15357830) (Similar question, but includes the separator elements in the output) – Aran-Fey Oct 22 '18 at 19:05
  • @Aran-Fey this answer answers perfectly, that said: https://stackoverflow.com/a/15358422/6451573, in the first part (even if it's not the output that OP needs) – Jean-François Fabre Oct 22 '18 at 20:52

1 Answers1

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]
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219