简体   繁体   中英

Python - Finding index of first empty item in a list

I am trying to find the index of the first empty item from the following list:

list_ = [10000.0, 6000.0, nan, nan, nan]

and to show the correct output as an index of:

2

I have been referring to the code from this link but I keep receiving the "StopIteration:" error message. Does anyone have the solution to this?

This is the code that I have so far:

try:
    next(i for i, j in enumerate(list_) if j == "nan")
except StopIteration:
    pass

Your check condition is wrong, it tries to find an item equal to string "nan" . To check if a float var is nan, use math.isnan(j) .

This one is a little tricky, because nan is not equal to itself.

However, your current solution is easily adaptable using isnan :

import math

try:
    index = next(i for i, j in enumerate(list_) if math.isnan(j))
except StopIteration:
    # nan is not in the list 
    pass

Might be a more pythonic way to do this, but this is what I would do:

from numpy import nan, isnan

list_ = [10000.0, 6000.0, nan, nan, nan]

for ind, elem in enumerate(list_):
    if isnan(elem):
        print ind
        break

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