Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select elements in a list by the occurrence of zeros in python

Given a 2D list:

X = [ [a,2], [b,12], [c,6], [d,0], [e,2], [f,0], [g,0], [h,12], [i,18] ]

I need to get a 2D list that groups all the sublists, separated by zeros in the X[1] column. I mean, I need to select:

Y = [ [[a,2],[b,12],[c,6]], [[e,2]], [[h,12],[i,18]] ]

ang get a list of the corresponding X[0] entries only:

Y = [ [a, b, c], [e], [h, i] ]

I've already asked a similar question for selecting elements within a list, on the basis of the occurrences of zeros inside it, but it was a 1D list. Using itertools, I tried something like:

Z = [list(v) for k, v in itertools.groupby(X[:,1], lambda x: x == 0) if not k] 

where I used X[:,1] to act on the X[1] part of the list, as the selection acts on it. But it obviously gives me the X[1] part of the list:

Z = [[2, 12, 6], [2], [12, 18]]

But I need the X[0] column... how can I use itertools on multi-dimensional lists? Thanks in advance.

like image 351
urgeo Avatar asked Feb 04 '26 02:02

urgeo


1 Answers

I believe this will do the work:

[map(lambda a:a[0],list(v)) for k, v in itertools.groupby(X, lambda x: x[1] == 0) if not k]

More explanation:

you want to groupby X according to the second value of each item in the list so you need to do:
itertools.groupby(X, lambda x: x[1] == 0)

[list(v) for k, v in itertools.groupby(X, lambda x: x[1] == 0) if not k] will create the 2D list like that:
[[['a', 2], ['b', 12], ['c', 6]], [['e', 2]], [['h', 12], ['i', 18]]] so you need to manipulate each item in the list and take only the second index, this can be done with the map function:

[map(lambda a:a[0],list(v)) for k, v in itertools.groupby(X, lambda x: x[1] == 0) if not k]
like image 55
Elisha Avatar answered Feb 05 '26 19:02

Elisha