在 Python 中迭代 N 维

发布于 2024-09-18 16:27:51 字数 634 浏览 8 评论 0原文

我有一个地图,我们称之为 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)它将产生正确的三元组序列。

是的,我自己也尝试过,但我的头爆炸了。或者我无法证明花时间去解决它,即使它很有趣。任君选择:)

I have a map, let's call it M, which contains data mapped through N dimensions.

# 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.

My question is: How do I make an iterator that can yield the correct iteration sequence? That is, given start, size = (10, 10), (3, 3) it would yield the 2-tuple sequence (10, 10), (10, 11), (10, 12), (11, 10), (11, 11) etc. And given start, size = (10, 10, 10), (3, 3, 3) it would yield the correct 3-tuple sequence.

Yeah, I tried myself, but my head exploded. Or I can't justify spending time figuring it out, even though it's fun. Take your pick :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

悍妇囚夫 2024-09-25 16:27:51

在 Python 2.6+ 中:

itertools.product(*[xrange(i, i+j) for i,j in zip(start, size)])

In Python 2.6+:

itertools.product(*[xrange(i, i+j) for i,j in zip(start, size)])
懷念過去 2024-09-25 16:27:51

使用 do it 你自己生成表达式:

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

With do it your self generator expreessions:

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文