简体   繁体   English

python:单行笛卡儿积分for循环

[英]python: single-line cartesian product for-loop

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? 是否存在for循环版本或只能为列表推导执行此操作?

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

Well there's no syntax for what you want, but there is itertools.product . 好吧,没有你想要的语法,但有itertools.product

>>> import itertools
>>> for x, y in itertools.product([1,2,3,4], [5,6,7,8]): print x, y
... 
1 5
1 6
1 7
1 8
[ ... and so on ... ]

That is an equivalent, more compact version of: 这是一个等效的,更紧凑的版本:

def values():
    for x in xrange(2):
        for y in xrange(5):
            yield (x, y)
list(values())

Update : To compare bytecode of both, do this: 更新 :要比较两者的字节码,请执行以下操作:

import dis
print dis.dis(values)   # above function

gen = ((x,y) for x in xrange(2) for y in xrange(5))
print dis.dis(gen.gi_code)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM