在 Python 中迭代 N 维
我有一个地图,我们称之为 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Python 2.6+ 中:
In Python 2.6+:
使用 do it 你自己生成表达式:
With do it your self generator expreessions: