索引for循环中的当前值?蟒蛇

Rim*_*oun 3 python

所以我有一个for循环.

>>> row = [5, 2, 5, 4, 2, 2, 5, 5, 5, 2]
>>> for i in row:
    if i == 5:
        print(row.index(i))
    if i == 2:
        print(row.index(i))
Run Code Online (Sandbox Code Playgroud)

OUTPUT

0
1
0
1
1
0
0
0
1
Run Code Online (Sandbox Code Playgroud)

我想得到:0 1 2 4 5 6 7 8 9.换句话说,我想得到i我正在for循环中看到的索引,如果它是= 5或2 ...任何简单的方法来做到这一点?

Mar*_*ers 7

使用该enumerate()函数生成运行索引:

for index, i in enumerate(row):
    if i == 5:
        print(index)
    if i == 2:
        print(index)
Run Code Online (Sandbox Code Playgroud)

或者更简单:

for index, i in enumerate(row):
    if i in (2, 5):
        print(index)
Run Code Online (Sandbox Code Playgroud)