python:单行笛卡尔积for循环

发布于 2024-11-02 15:46:05 字数 604 浏览 0 评论 0原文

你知道你能做到吗?

>>> [(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 技术交流群。

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

发布评论

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

评论(2

梦断已成空 2024-11-09 15:46:05

好吧,没有您想要的语法,但是有 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 ... ]

Well there's no syntax for what you want, but there is 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 ... ]
九八野马 2024-11-09 15:46:05

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

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)

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