user3375672
user3375672

Reputation: 3768

python: find the indeces of nested list by condition

To get the list indeces that satifies a condition, say None I can do:

[x for (x, e) in enumerate(my_list) if e is None]

But I can not get my head around what to do with a nested list using the same scheme as above. For instance how to find the indeces of my_nlist where the first element in the nested (inner) lists are None.

my_nlist = [[None, 2], [13, 2], [None, 1]]

The expected result would be: [0,2]

Upvotes: 2

Views: 231

Answers (2)

Colonel Beauvel
Colonel Beauvel

Reputation: 31171

An approach with numpy (maybe clearer than base python but needs a library):

import numpy as np

np.where([None in i for i in L])

#(array([0, 2], dtype=int64),)

Upvotes: 3

Kasravnd
Kasravnd

Reputation: 107287

Same as the previous one just use a tuple as the items throwaway variable:

In [5]: [ind for ind, (i, j) in enumerate(my_nlist) if i is None]
Out[5]: [0, 2]

Upvotes: 4

Related Questions