python - 在 Python 中创建一个 "actual"for 循环?

标签 python loops

你应该知道,在 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/

相关文章:

javascript - 如何在同一个 for 循环中声明一个新对象而不覆盖之前的迭代?

python - For 循环运行直到达到变量值

r - 简化可怕的 R 代码以调整行均值

python - 使用 AND 条件查询单行 DataFrame

types - Python:测试值是否可以在列表理解中转换为 int

Python:创建一个从注释中删除的文件副本

python - 同时循环三个列表 : nested loop not working

python - 扭曲 deferToThread 中的延迟中未处理的错误

python - 程序阻止鼠标移动

Ruby 的 "each"方法没有遍历数组中的所有项目?