2012-10-25 44 views
1

我想有一个列表理解动态大小的Python列表理解

[x,y,z] for x in a for y in a for z in a 

假设这是理解我得到了规模3 我希望能够相应地修改它,2我只会有X ,y为4我会像a,b,c,d等...

有没有办法做到这一点?

+0

有可能已经是一个解决方案,但你将不得不澄清这个问题有点进一步。 –

+0

'[x,y,z] for x in a for for y in a for z in a'是无效的Python语法。你的意思是[[x,y,z] for a for for y in a for z in a]'?如果不是,你想做什么? – NullUserException

+0

我认为你的意思是:'for x in a for y in b for z in c in c'? –

回答

6

是的,你可以使用product功能:

from itertools import product 
a = [1,2,3] 
print list(product(a)) 
# gives: [(1,), (2,), (3,)] 
print list(product(a, a)) 
# gives: [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)] 
print list(product(a, a, a)) 
# gives: [(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 1), (1, 3, 2), (1, 3, 3), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 1), (2, 3, 2), (2, 3, 3), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 3, 1), (3, 3, 2), (3, 3, 3)] 

,或者更方便与repeat关键字:

product(a, repeat=3) 
+2

值得一提的是'repeat'关键字参数。 – DSM

+1

@DSM:好点。这意味着上面也可以用'product(a,repeat = 3)'完成。 –

+0

对不起,我不清楚这不完全是我想要的。 为每个元素x y z等...我选择了两个元素之一。我不能选择两个,我只是想要获得所有组合,我为每个元素选择一个或另一个。而不是整个交叉产品 – Lemonio