der*_*tar 2 python position list
我有一个列表,如:
[1,2,3,2,1,5,6]
Run Code Online (Sandbox Code Playgroud)
我想在列表中找到1的所有位置.我试过if语句,但我只获得前1的位置,而不是所有的1.
如果我使用if语句的实际输出[0],但预期的结果应该是[0,4].
您可以使用列表推导迭代enumerate(your_list)并使用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]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
448 次 |
| 最近记录: |