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
What would be the 'pythonic' way of achieving this ?
nonzero() function is used to Compute the indices of the elements that are non-zero. It returns a tuple of arrays, one for each dimension of arr, containing the indices of the non-zero elements in that dimension. The corresponding non-zero values in the array can be obtained with arr[nonzero(arr)] .
The list index() method helps you to find the index of the given element. This is the easiest and straightforward way to get the index. The list index() method returns the index of the given element.
One of the most basic ways to get the index positions of all occurrences of an element in a Python list is by using a for loop and the Python enumerate function. The enumerate function is used to iterate over an object and returns both the index and element.
Use the nonzero() Function to Find the First Index of an Element in a NumPy Array. The nonzero() function returns the indices of all the non-zero elements in a numpy array. It returns tuples of multiple arrays for a multi-dimensional array.
[i for i, e in enumerate(a) if e != 0]
Not really a "new" answer but numpy has this built in as well.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With