如何在python的列表中返回与输入数字相同的数字位置? [英] How to return the position of numbers, which are same as input numbers, in a list in python?

查看:329
本文介绍了如何在python的列表中返回与输入数字相同的数字位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,例如:

[1,2,3,2,1,5,6] 

我想找到列表中1的所有位置.我尝试了if语句,但只得到前1个位置,而不是全部1.

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.

如果使用if语句,则实际输出看起来像[0],但预期结果应该是[0,4].

The real output if I use if statement looks like [0], but the expected result should be [0,4].

推荐答案

您可以使用列表理解遍历 enumerate(your_list) 并使用if语句作为它仅捕获所需的值,如下所示:

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]

这篇关于如何在python的列表中返回与输入数字相同的数字位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆