Python 如何获取列表中非零元素的索引列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4111412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:18:45  来源:igfitidea点击:

How do I get a list of indices of non zero elements in a list?

listpythonlist-comprehension

提问by George Profenza

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:

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

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

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

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

采纳答案by Ignacio Vazquez-Abrams

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

回答by John La Rooy

Since THC4k mentioned compress (available in python2.7+)

由于 THC4k 提到了压缩(在 python2.7+ 中可用)

>>> from itertools import compress, count
>>> x = [0, 1, 0, 1, 0, 0, 0, 0]
>>> compress(count(), x)
<itertools.compress object at 0x8c3666c>   
>>> list(_)
[1, 3]

回答by Brian Larsen

Not really a "new" answer but numpyhas this built in as well.

不是真正的“新”答案,但numpy也内置了这个。

import numpy as np
a = [0, 1, 0, 1, 0, 0, 0, 0]
nonzeroind = np.nonzero(a)[0] # the return is a little funny so I use the [0]
print nonzeroind
[1 3]

回答by Lexa

Just wished to add explanation for 'funny' output from the previous asnwer. Result is a tuple that contains vectors of indexes for each dimension of the matrix. In this case user is processing what is considered a vector in numpy, so output is tuple with one element.

只是想为上一个答案的“有趣”输出添加解释。结果是一个元组,其中包含矩阵每个维度的索引向量。在这种情况下,用户正在处理 numpy 中被视为向量的内容,因此输出是具有一个元素的元组。

import numpy as np
a = [0, 1, 0, 1, 0, 0, 0, 0]
nonzeroind = np.nonzero(a) 
print nonzeroind
(array([1, 3]),)