1

如您所知,在 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

但就我而言,我不能这样做。

4

2 回答 2

9

为什么需要 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)

如果你一心想模拟一个反跟踪循环,你就有了一个图灵完备的语言,这可以做到:

# ...but why?
counter = 0
while counter < upper_bound:
  # do stuff
  counter += 1

如果您觉得有必要在循环中重新分配循环计数器变量,那么您做错的可能性很高,无论是 C 循环还是 Python 循环。

于 2013-10-14T18:00:14.427 回答
9

我从您的评论中猜想您正在尝试遍历网格索引。这里有一些方法:

简单的双 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
于 2013-10-14T18:19:07.020 回答