1

How can I split a list of integers based on specific value? See following example for instance:

inp = [1, 3, 4, 5, -999, 0, 0, 1, 3, 5, -999, 85, 82, 84]

outs = magic_function(inp)

>> [[1,3,4,5], [0,0,1,3,5], [85,82,84]] # expected output is like this

The output will be a list of list which splited based on -999. So far I handle it with for-loop or convert it to string and then use str.split('-999') but I would like to know is there any elegant (more efficient) way to do this?

Amir
  • 16,067
  • 10
  • 80
  • 119
  • In the above link, [this particular answer](https://stackoverflow.com/a/15358422/2296458) has a one-line solution to do just this – Cory Kramer Oct 16 '20 at 12:06

1 Answers1

1

this would work:

from itertools import groupby

inp = [1, 3, 4, 5, -999, 0, 0, 1, 3, 5, -999, 85, 82, 84]

sep = -999
ret = [list(items) for key, items in groupby(inp, lambda x: x == sep) if not key]

print(ret)  # [[1, 3, 4, 5], [0, 0, 1, 3, 5], [85, 82, 84]]

where i use itertools.groupby to split the list.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111