【发布时间】:2011-08-06 14:27:03
【问题描述】:
有没有更简洁的替代方法:
for x in xrange(array.shape[0]):
for y in xrange(array.shape[1]):
do_stuff(x, y)
我想出了这个:
for x, y in itertools.product(map(xrange, array.shape)):
do_stuff(x, y)
这节省了一个缩进,但仍然很丑。
我希望看起来像这样的伪代码:
for x, y in array.indices:
do_stuff(x, y)
有类似的东西吗?
【问题讨论】:
-
我在 python 2.7 中并且正在使用您的解决方案和 itertools;我在 cmets 中读到使用 itertools 会更快。但是,(可能是因为我在 2.7 中)我还必须在 for 循环中解压缩 map。
for x, y in itertools.product(*map(xrange, array.shape)): -
NumPy 参考中有一个页面叫做“迭代数组”:docs.scipy.org/doc/numpy/reference/arrays.nditer.html