简体   繁体   中英

find indexes of all None items in a list in python

I have a list of strings, some of them are None. i want to get a new list of all the Indexes of None.

list = ['a', 'b', None, 'c' ,None, 'd']

using the function index

n = list.index(None)

will only return the first appearance, n= 2, while i want to see n= [2,4]. thanks you.

Try enumerate :

l=[i for i,v in enumerate(list) if v == None]

Or range :

l=[i for i in range(len(list)) if list[i] == None]

Both cases:

print(l)

Is:

[2,4]

Big Note: it is not good to name variables a existing method name, that overwrites it, (now it's list ), so i would prefer it as l (or something)

I recommend the first example because enumerate is easy, efficient.

Faster way. Very useful in case of long list.

list = ['a', 'b', None, 'c' ,None, 'd']
import numpy as np
print(np.where(np.array(list) == None)[0])

Output :

[2 4]

In case you need list of index :

print(np.where(np.array(list) == None)[0].tolist())
>>> [2, 4]

Here's something different but it doesn't use list comprehension:

>>> l = ['a', 'b', None, 'c' ,None, 'd']
>>> out = []
>>> for _ in range(l.count(None)):
    out.append(l.index(None))
    l[l.index(None)] = "w"


>>> out
[2, 4]
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM