您可以使用math.isnan() 编写通用自定义函数来获取列表中带有或不带有NaN 值的元素的索引。
from match import isnan
def nan_index(my_list, el):
if isinstance(el, float) and isnan(el):
for i, e in enumerate(my_list):
if isnan(e):
return i
else:
raise ValueError
else:
return my_list.index(el)
示例运行:
>>> nan_index([1, 2, 4, 5], 4) # For list of numbers
2
>>> nan_index(['a', 'b', 'c'], 'b') # For list of strings
1
>>> nan_index([1, 2, 4, float('nan')], float('nan')) # For list with `NaN`
3
>>> nan_index([1, 2, 4, 5], float('nan')) # "ValueError", for list without match
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in nan_index
ValueError