Frage

Say I have two lists

a = [True, True, True, False, False, True, False]
b = [1, 2, 1, 3, 2, 1, 0]

I can group one list into similar items:

import itertools
b =  [list(g) for k, g in itertools.groupby(a)]
>>> [[True, True, True], [False, False], [True], [False]] 

Is there a convenient way to apply this operation to the other list to give:

>>> [[1,2,1], [3,2], [1], [0]]

This works but is there something nicer:?

new_list = []
index = 0
for i in b:
    length = len(i)
    new_list.append(y[index:index+length])
    index += length

Thanks

War es hilfreich?

Lösung

You can groupby on enumerate(a):

>>> from itertools import groupby
>>> from operator import itemgetter
>>> indices = ((x[0] for x in g) for _, g in groupby(enumerate(a), key=itemgetter(1)))
>>> [[b[x] for x in lst] for lst in indices]
[[1, 2, 1], [3, 2], [1], [0]]

Andere Tipps

from itertools import groupby, izip
groups = [list(grp) for _, grp in groupby(izip(a, b), lambda x: x[0])]
print [[number for _, number in items] for items in groups]
# [[1, 2, 1], [3, 2], [1], [0]]
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top