umpalumpa__
umpalumpa__

Reputation: 93

find all elements and indices larger than threshold in list of lists

I have a list of lists like:

  j=[[1,2,3],[4,5,6],[7,8,9,10],[11,12,13,14,15]]

and I want to get a list of all elements from the list of lists larger than a certain threshold. I know when having a list there is the Syntax:

k=[1,2,3,4,5,6,7]
k2=[i for i in k if i>5]
k2=[6,7]

Is there a similar way when having a lists of lists as an Input? Is it additionally possible to get the indices of the elements larger than that threshold?

Upvotes: 0

Views: 2275

Answers (1)

xnx
xnx

Reputation: 25478

Is this what you mean?

In [3]: l1 = [[1,2,3],[4,5,6],[7,8,9,10],[11,12,13,14,15]]
In [4]: [e for l2 in l1 for e in l2 if e>5]
Out[4]: [6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

To get the index (of the inner lists), you can use enumerate:

In [5]: [(i2, e) for l2 in l1 for i2, e in enumerate(l2) if e>5]

Out[5]: 
[(2, 6),
 (0, 7),
 (1, 8),
 (2, 9),
 (3, 10),
 (0, 11),
 (1, 12),
 (2, 13),
 (3, 14),
 (4, 15)]

If you want the indices in a separate list (un)zip:

In [6]: list(zip(*[(i2, e) for l2 in l1 for i2, e in enumerate(l2) if e>5]))

Out[6]: [(2, 0, 1, 2, 3, 0, 1, 2, 3, 4), (6, 7, 8, 9, 10, 11, 12, 13, 14, 15)]

[You don't need the list call if you're using Python 2]. A similar approach will give you indexes into both the outer and inner lists:

In [7]: [((i1,i2), e) for (i1,l2) in enumerate(l1) for i2, e in enumerate(l2) if e>5]
Out[7]: 
[((1, 2), 6),
 ((2, 0), 7),
 ((2, 1), 8),
 ((2, 2), 9),
 ((2, 3), 10),
 ((3, 0), 11),
 ((3, 1), 12),
 ((3, 2), 13),
 ((3, 3), 14),
 ((3, 4), 15)]

or, unzipped:

In [8]: idx, items = list(zip(*[((i1,i2), e) for (i1,l2) in enumerate(l1)
                                    for i2, e in enumerate(l2) if e>5]))

In [8]: idx
Out[8]: 
((1, 2),
 (2, 0),
 (2, 1),
 (2, 2),
 (2, 3),
 (3, 0),
 (3, 1),
 (3, 2),
 (3, 3),
 (3, 4))

In [9]: items
Out[9]: (6, 7, 8, 9, 10, 11, 12, 13, 14, 15)

Upvotes: 6

Related Questions