0

我是使用 python 编程和一般编程的新手,并且遇到以下问题:

b=["hi","hello","howdy"]
for i in b:
    print i

#This code outputs:
hi
hello
howdy

我怎样才能使它的迭代变量是一个 int 所以它的工作方式如下?

b=["hi","hello","howdy"]
for i in b:
    print i

#I want it to output:
0
1
2
4

3 回答 3

4

Pythonic 的方式是enumerate()

for index, item in enumerate(b):
    print index, item

还有range(len(b)),但您几乎总是会item在循环体中检索,因此enumerate()大多数情况下是更好的选择:

for index in range(len(b)):
    print index, b[index]
于 2013-10-08T22:29:02.710 回答
3
b=["hi","hello","howdy"]
for count,i in enumerate(b):
    print count
于 2013-10-08T22:29:11.470 回答
1

你总是可以这样做:

b=["hi","hello","howdy"]
for i in range(len(b)):
    print i
于 2013-10-08T22:34:47.123 回答