[英]How can I iterate over a list of strings with ints in python?
I'm new to programming with python and programming in general and got stuck wit the following problem: 我是使用python进行编程和一般编程的新手,并且遇到以下问题:
b=["hi","hello","howdy"]
for i in b:
print i
#This code outputs:
hi
hello
howdy
How can I make it so the iterating variable is an int so it works the following way? 我怎样才能使迭代变量是一个整数,所以它可以按以下方式工作?
b=["hi","hello","howdy"]
for i in b:
print i
#I want it to output:
0
1
2
The Pythonic way would be with enumerate()
: Python的方式是
enumerate()
:
for index, item in enumerate(b):
print index, item
There's also range(len(b))
, but you almost always will retrieve item
in the loop body, so enumerate()
is the better choice most of the time: 还有
range(len(b))
,但是您几乎总是会在循环主体中检索item
,因此enumerate()
在大多数情况下是更好的选择:
for index in range(len(b)):
print index, b[index]
b=["hi","hello","howdy"]
for count,i in enumerate(b):
print count
you could always do this: 您可以始终这样做:
b=["hi","hello","howdy"]
for i in range(len(b)):
print i
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.