Input: array=[3, 4, 7, 0, 2, 3, 0, 6, 3, 0] or any integer array. Output: 3, 6, 9
arr = [1,0,2,3,0,4,5,0]
item = 0
index1 = arr.index(item)
start1=(index1 1)
index2 = arr.index(item,start1)
start2=(index2 1)
index3 = arr.index(item,start2)
print(index1)
print(index2)
print(index3)
I don't know how to find the index except for the index. Help those to do so that would find all the indexes of zero.
CodePudding user response:
I would suggest something like this:
arr = [1,0,2,3,0,4,5,0]
indexes = [] # list which contains the indexes of zeros
for i, v in enumerate(arr): # Iterate over indexes and values (i and v)
if (not v): # Equivalent to if (v == 0) in the case of an integer array
indexes.append(i)
At the end you will have in indexes
all the indexes of the zeros of arr
:
>>> indexes
[1, 4, 7]
I would suggest you to read the documentation about enumerate
to better understand the code.
CodePudding user response:
This can be done with a generator as follows:
array = [3, 4, 7, 0, 2, 3, 0, 6, 3, 0]
print(', '.join(str(i) for i, v in enumerate(array) if v == 0))
Output:
3, 6, 9