在for循环中查找元素的索引

时间:2014-10-06 20:11:34

标签: python

是否有可能在Python中制作这样的东西?

a = ["h", "e", "l", "l", "o"]
for letter in a:
    print #I want to obtain a[0] or a[1] or a[2]...

提前致谢。我知道标题不是很明确,但我不知道如何正确解释。

1 个答案:

答案 0 :(得分:3)

使用enumerate

a = ["h", "e", "l", "l", "o"]
for idx, letter in enumerate(a):
    print "a[", idx, "] contains the letter", letter

结果:

a[ 0 ] contains the letter h
a[ 1 ] contains the letter e
a[ 2 ] contains the letter l
a[ 3 ] contains the letter l
a[ 4 ] contains the letter o