我有一张地图,我们称之为M,其中包含通过N维映射的数据。
# If it was a 2d map, I could iterate it thusly:
start, size = (10, 10), (3, 3)
for x in range(start[0], start[0]+size[0]):
for y in range(start[1], start[1]+size[1]):
M.get((x, y))
# A 3d map would add a for z in ... and access it thusly
M.get((x, y, z))
# And so on.
我的问题是:如何创建一个可以产生正确迭代序列的迭代器?也就是说,给定start, size = (10, 10), (3, 3)
它将产生2元组序列(10, 10), (10, 11), (10, 12), (11, 10), (11, 11)
等。并且给定start, size = (10, 10, 10), (3, 3, 3)
它将产生正确的3元组序列。
答案 0 :(得分:8)
在Python 2.6 +中:
itertools.product(*[xrange(i, i+j) for i,j in zip(start, size)])
答案 1 :(得分:0)
自己做生成器表达式:
start, size = (10, 10), (3, 3)
values2=((x+xd,y+yd)
for x,y in (start,)
for xr,yr in (size,)
for xd in range(xr)
for yd in range(yr))
for x,y in values2:
print x,y
start, size = (10, 10, 10), (3, 3, 3)
values3=((x+xd,y+yd, z+zd)
for x,y,z in (start,)
for xr,yr,zr in (size,)
for xd in range(xr)
for yd in range(yr)
for zd in range(zr))
for x,y,z in values3:
print x,y,z