如何获得列表中非零元素的索引列表? [英] How do I get a list of indices of non zero elements in a list?

查看:74
本文介绍了如何获得列表中非零元素的索引列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个始终只包含一和零的列表. 我需要获取列表的非零索引列表:

I have a list that will always contain only ones and zeroes. I need to get a list of the non-zero indices of the list:

a = [0, 1, 0, 1, 0, 0, 0, 0]
b = []
for i in range(len(a)):
    if a[i] == 1:  b.append(i)
print b

实现这一目标的"pythonic"方式是什么?

What would be the 'pythonic' way of achieving this ?

推荐答案

[i for i, e in enumerate(a) if e != 0]

这篇关于如何获得列表中非零元素的索引列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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