在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)))