Python-查找列表中第一个非空项目的索引

问题描述:

在Python中查找列表中第一个非空项目的索引的最有效/最优雅的方法是什么?

What would be the most efficient\elegant way in Python to find the index of the first non-empty item in a list?

例如,使用

list_ = [None,[],None,[1,2],'StackOverflow',[]]

正确的非空索引应为:

3

>>> lst = [None,[],None,[1,2],'StackOverflow',[]]
>>> next(i for i, j in enumerate(lst) if j)
3

如果您不想引发StopIteration错误,只需为next函数提供默认值即可:

if you don't want to raise a StopIteration error, just provide default value to the next function:

>>> next((i for i, j in enumerate(lst) if j == 2), 42)
42

P.S.不要使用list作为变量名,它会隐藏内置变量.

P.S. don't use list as a variable name, it shadows built-in.