How to return the position of numbers, which are same as input numbers, in a list in python?

蹲街弑〆低调 提交于 2019-12-24 01:03:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!