python:单行笛卡尔积for循环
你知道你能做到吗?
>>> [(x,y) for x in xrange(2) for y in xrange(5)]
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4)]
很整洁。是否有 for 循环版本或者只能对列表理解执行此操作?
编辑:我认为我的问题被误解了。我想知道是否有特殊的语法:
for x in xrange(2) <AND> y in xrange(5):
print "do stuff here"
print "which doesn't fit into a list comprehension"
print "like printing x and y cause print is a statement", x, y
我可以这样做,但似乎有点重复:
for x,y in ((x,y) for x in xrange(2) for y in xrange(5)):
print x, y
Did you know you can do this?
>>> [(x,y) for x in xrange(2) for y in xrange(5)]
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4)]
It's neat. Is there a for loop version or can one only do this for list comprehensions?
EDIT: I think my question was misunderstood. I want to know if there is special syntax for this:
for x in xrange(2) <AND> y in xrange(5):
print "do stuff here"
print "which doesn't fit into a list comprehension"
print "like printing x and y cause print is a statement", x, y
I could do this, but it seems a bit repetitive:
for x,y in ((x,y) for x in xrange(2) for y in xrange(5)):
print x, y
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,没有您想要的语法,但是有
itertools.product
。Well there's no syntax for what you want, but there is
itertools.product
.这是一个等效的、更紧凑的版本:
更新:要比较两者的字节码,请执行以下操作:
That is an equivalent, more compact version of:
Update: To compare bytecode of both, do this: