正如您应该知道的,在Python中,以下是Python中有效的for循环:
animals = [ 'dog', 'cat', 'horse' ] # Could also be a dictionary, tuple, etc
for animal in animals:
print animal + " is an animal!"
Run Code Online (Sandbox Code Playgroud)
这通常很好.但在我的情况下,我想像在C/C++/Java等中那样创建一个for循环.for循环看起来像这样:
for (int x = 0; x <= 10; x++) {
print x
}
Run Code Online (Sandbox Code Playgroud)
我怎么能在Python中做这样的事情?我是否必须设置这样的东西,或者是否有一种实际的方法可以做到这一点我缺少(我已经用Google搜索了好几周):
i = 0
while i is not 10:
print i
Run Code Online (Sandbox Code Playgroud)
或者有一个如何做到这一点的标准?我发现以上并不总是有效.是的,对于上述情况,我可以这样做:
for i in range(10):
print i
Run Code Online (Sandbox Code Playgroud)
但就我而言,我不能这样做.
为什么需要C风格的索引跟踪循环?我可以想象一些案例.
# Printing an index
for index, name in enumerate(['cat', 'dog', 'horse']):
print "Animal #%d is %s" % (index, name)
# Accessing things by index for some reason
animals = ['cat', 'dog', 'horse']
for index in range(len(animals)):
previous = "Nothing" if index == 0 else animals[index - 1]
print "%s goes before %s" % (previous, animals[index])
# Filtering by index for some contrived reason
for index, name in enumerate(['cat', 'dog', 'horse']):
if index == 13:
print "I am not telling you about the unlucky animal"
continue # see, just like C
print "Animal #%d is %s" % (index, name)
Run Code Online (Sandbox Code Playgroud)
如果你真的很想模仿一个反跟踪循环,你就有了图灵完备的语言,这可以做到:
# ...but why?
counter = 0
while counter < upper_bound:
# do stuff
counter += 1
Run Code Online (Sandbox Code Playgroud)
如果您觉得有必要重新分配循环计数器变量中间循环,那么你做错了很可能很高,无论是C循环还是Python循环.
小智 9
我猜从你的评论中你试图循环网格索引.以下是一些方法:
简单的双循环:
for i in xrange(width):
for j in xrange(height):
blah
Run Code Online (Sandbox Code Playgroud)
使用itertools.product
for i, j in itertools.product(xrange(width), xrange(height)):
blah
Run Code Online (Sandbox Code Playgroud)
如果可以,使用numpy
x, y = numpy.meshgrid(width, height)
for i, j in itertools.izip(x.reshape(width * height), y.reshape(width * height):
blah
Run Code Online (Sandbox Code Playgroud)