python单行循环_python:单行笛卡尔积for循环

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) 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.

>>> 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 ... ]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值