你应该知道,在 Python 中,以下是 Python 中有效的 for 循环:
animals = [ 'dog', 'cat', 'horse' ] # Could also be a dictionary, tuple, etc
for animal in animals:
print animal + " is an animal!"
这通常没问题。但就我而言,我想像在 C/C++/Java 等中那样创建一个 for 循环。for 循环如下所示:
for (int x = 0; x <= 10; x++) {
print x
}
我怎么能在 Python 中做这样的事情呢?我是否必须设置这样的东西,或者是否有我缺少的实际方法(我已经用谷歌搜索了好几个星期):
i = 0
while i is not 10:
print i
或者是否有关于如何执行此操作的标准?我发现上述并不总是有效。是的,对于上述情况我可以这样做:
for i in range(10):
print i
但就我而言,我不能这样做。
最佳答案
我从您的评论中猜想您正在尝试遍历网格索引。以下是一些方法:
简单的双 for 循环:
for i in xrange(width):
for j in xrange(height):
blah
使用 itertools.product
for i, j in itertools.product(xrange(width), xrange(height)):
blah
尽可能使用 numpy
x, y = numpy.meshgrid(width, height)
for i, j in itertools.izip(x.reshape(width * height), y.reshape(width * height):
blah
关于python - 在 Python 中创建一个 "actual"for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19376732/