Python-查找列表中第一个非空项目的索引 [英] Python - Finding index of first non-empty item in a list

查看:103
本文介绍了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.

这篇关于Python-查找列表中第一个非空项目的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆