python:单行笛卡尔积for循环 [英] python: single-line cartesian product for-loop
本文介绍了python:单行笛卡尔积for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
>>>你知道你可以做这个吗? (0),(0,1),(0,2),(0,3),(x,y)的xrange(2)中的x的[(x,y))。 (0,4),(1,0),(1,1),(1,2),(1,3),(1,4)]
它很整齐。有一个for循环版本,或者只能做一个列表解析?
编辑:我想我的问题被误解了。我想知道是否有特殊的语法:
for xrange(2)< AND> y在xrange(5)中:
printdo stuff here
print哪个不适合列表理解
print就像打印x和y导致print是一个语句 ,x,y
我可以这样做,但似乎有点重复:
$ (b)(b)(b)(b)b$ b pre $
print x,y
解决方案
想要,但有
itertools.product
。 >>> import itertools
>>> for itertools.product([1,2,3,4],[5,6,7,8])中的x,y:print x,y
...
1 5
1 6
1 7
1 8
[...等等...]
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
解决方案
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 ... ]
这篇关于python:单行笛卡尔积for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文