如何在python中使用int迭代字符串列表?

时间:2013-10-08 22:27:36

标签: python variables loops int

我不熟悉使用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

3 个答案:

答案 0 :(得分: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]

答案 1 :(得分:3)

b=["hi","hello","howdy"]
for count,i in enumerate(b):
    print count

答案 2 :(得分:1)

你总是可以这样做:

b=["hi","hello","howdy"]
for i in range(len(b)):
    print i