python - 在for循环中索​​引当前值? Python

标签 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))

输出

0
1
0
1
1
0
0
0
1

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

最佳答案

使用 enumerate() function生成运行索引:

for index, i in enumerate(row):
    if i == 5:
        print(index)
    if i == 2:
        print(index)

或更简单:

for index, i in enumerate(row):
    if i in (2, 5):
        print(index)

关于python - 在for循环中索​​引当前值? Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22267488/

相关文章:

python - 寻找一种在 Django admin 中显示代码块的简单方法

python - 如何将字符串的长度转换为字节?

python - 如何在 PostgreSQL 数据库中存储 NumPy 数组?

python - 更改子图中 matplotlib fiddle 图的颜色

python - 如何使用 H5py 在 python 3 中正确打开、读取和保存单个文件

python - 如何摆脱 PyCharm 中的库根标记

python - 如何将 codeskulptor 中的代码从浏览器移动到 python 2.7?

python - 如何沟通两个独立的python进程?

python - python中时区切换时不一致

python - 在 git-python 中通过 hexsha 获取 Commit 对象