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

时间:2011-04-22 20:30:14

标签: python for-loop list-comprehension

你知道你能做到吗?

>>> [(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

2 个答案:

答案 0 :(得分:7)

没有你想要的语法,但有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 ... ]

答案 1 :(得分:5)

这是一个等效的,更紧凑的版本:

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

更新:要比较两者的字节码,请执行以下操作:

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)