问题
I have a list such as:
[1,2,3,2,1,5,6]
I want to find the all the positions of 1 in the list. I tried if statement, but I only get the position of first 1, not all 1s.
The real output if I use if statement looks like [0]
, but the expected result should be [0,4]
.
回答1:
You can use a list comprehension iterating over enumerate(your_list) and using an if
statement as part of it to catch only the wanted values, as below:
data = [1,2,3,2,1,5,6] # Your list
num = 1 # The value you want to find indices for
pos = [i for i, v in enumerate(data) if v == num]
print(pos)
# [0, 4]
回答2:
Try using enumerate:-> this give a tuple with its index
and value
from the list
lndexs=[]
for index,value in enumerate([1,2,3,2,1,5,6]):
if value==1:
lndexs.append( index)
回答3:
lstOfNumbers = [1,2,3,2,1,5,6]
searchFor = 1
lstOfIndexs = [index for index in range(len(lstOfNumbers)) if lstOfNumber[index]==searchFor]
Or you can use the python function filter
lstOfNumbers = [1,2,3,2,1,5,6]
searchFor = 1
lstOfIndexs = filter(lambda x: lstOfNumbers[x]==searchFor, range(len(lstOfNumbers)))
来源:https://stackoverflow.com/questions/25804259/how-to-return-the-position-of-numbers-which-are-same-as-input-numbers-in-a-lis