1

I have a list of values, 7,7,7,7,7,7,7,7,6,6,6,6,6,6,7,7,7,7,7,8,8,8,8,8,8,8,8,5,5,5,5,5,5,6,6,6,6,6 etc and I need to split the list into the list of list format every time there is a change in value, such that it becomes [[7,7,7,7,7,7,7,7],[6,6,6,6,6,6],[7,7,7,7,7],[8,8,8,8,8,8,8,8],[5,5,5,5,5,5],[6,6,6,6,6]].

I tried a code as follows, however, it told me that there was an unexpected token "for". Is there any other way that's cleaner (one liners)?

for i, n in enumerate(x):
    inds = []
    if x[i] != x[i-1]:
        inds.append(i)
list(split_after(x, lambda i: i for i in inds))

Edit: I can't use groupby because it requires me to sort the list, and I'm concurrently using this list to sort another list of lines, and I can't reorder the other list because of how it's sorted to be lines running ordered around my entire surface.

Althea C
  • 109
  • 6
  • `i for i in` would just give you the same iterable as `inds` – Sayse Oct 29 '19 at 09:38
  • 2
    Specifically see the very first example here: https://stackoverflow.com/a/45873519/476 – deceze Oct 29 '19 at 09:42
  • @deceze groupby requires me to sort the list though, something I can't do as I need it to be exactly in the order it's presented, not by a sorted list. this is cuz i'm running it concurrently against another set of data, using it to split the other set of data. – Althea C Oct 29 '19 at 09:50
  • `groupby` will work on the list in the order it's in; you don't *have* to sort it, for your use case [it'll work exactly as you want it to work](https://repl.it/repls/CoralFlamboyantMode). – deceze Oct 29 '19 at 09:59
  • @AltheaC groupby does *not* require sorting the list. In fact, sorting will give you an *incorrect* output, if your sample example provided is accurate. – Paritosh Singh Oct 29 '19 at 10:06

1 Answers1

2

You can try the following:

indexes = [index for index, _ in enumerate(x) if x[index] != x[index-1]]
indexes.append(len(x))
final = [x[indexes[i]:indexes[i+1]] for i, _ in enumerate(indexes) if i != len(indexes)-1]

print(final)
Mehdi Khlifi
  • 405
  • 8
  • 21