Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中,如何返回与输入数字相同的数字在列表中的位置?_Python_List_Position - Fatal编程技术网

在python中,如何返回与输入数字相同的数字在列表中的位置?

在python中,如何返回与输入数字相同的数字在列表中的位置?,python,list,position,Python,List,Position,我有一份清单,例如: [1,2,3,2,1,5,6] 我想在列表中找到1的所有位置。我尝试了if语句,但我只得到了第一个1的位置,而不是所有的1 if use if语句的实际输出看起来像[0],但预期结果应该是[0,4]您可以使用迭代并使用if语句作为其一部分,以仅捕获所需的值,如下所示: 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

我有一份清单,例如:

[1,2,3,2,1,5,6] 
我想在列表中找到1的所有位置。我尝试了if语句,但我只得到了第一个1的位置,而不是所有的1

if use if语句的实际输出看起来像
[0]
,但预期结果应该是
[0,4]

您可以使用迭代并使用
if
语句作为其一部分,以仅捕获所需的值,如下所示:

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]

尝试使用enumerate:->这将给出一个元组,其中包含列表中的
索引

 lndexs=[]
 for index,value in enumerate([1,2,3,2,1,5,6]):
        if value==1:
            lndexs.append( index)
或者可以使用python函数过滤器

lstOfNumbers = [1,2,3,2,1,5,6]
searchFor = 1    
lstOfIndexs = filter(lambda x: lstOfNumbers[x]==searchFor, range(len(lstOfNumbers)))

请分享你的代码,虽然它给了你错误的输出?这些职位将如何成为用户?也许你根本不需要它们,问题解决了!谢谢你的评论。
lstOfNumbers = [1,2,3,2,1,5,6]
searchFor = 1    
lstOfIndexs = filter(lambda x: lstOfNumbers[x]==searchFor, range(len(lstOfNumbers)))