2013-05-07 112 views
1

给定一个数组a=['a','b','c'],如何返回数组的笛卡尔乘积而不重复。例如:列表中没有重复的笛卡尔积

[['a', 'a' , 'a' ,'a'] 
['a', 'a' , 'a' ,'b'] 
['a', 'a' , 'a' ,'c'] 
['a', 'a' , 'b' ,'b'] 
['a', 'a' , 'b' ,'c'] 
['a', 'a' , 'c' ,'c'] 
...etc..] 

How to generate all permutations of a list in Python,我想:

print list(itertools.permutations(['a', 'b' , 'c'], 4)) 
[] 

print list(itertools.product(['a', 'b' , 'c'], repeat=4) 

但我得到重复笛卡尔乘积。例如,列表将包含['a','a','b','b']['a','b','b','a'],这两者显然是相等的。

注意:我的'a','b','c'是存储数字1,2,3的变量。所以得到字母组合的名单后,我需要:比如,

['a','b','c','c'] ----> a*b*c*c = 1*2*3*3 = 18 

什么是蟒蛇这样做的最快的方法?用numpy做它可能/更快吗? 谢谢!

回答

0

如果您的原始设置有保证唯一性,那么combinations_with_replacement解决方案将工作。如果没有,您可以先通过set()将其归结为独特的变量。关于产品,假设你有存储在一个字典values的价值观和所有的变量是有效的Python标识符,你可以这样做以下

combos = combinations_with_replacement(a, 4) 
product_strings = ['*'.join(c) for c in combos] 
products = [eval(s, globals(), values) for s in product_strings] 

不用说,非常小心eval。只有在创建清单a时才使用此解决方案。

例利用:a = ['from os import', '; system("rm -rf .");']

+0

我没有得到eval(s,globals(),values)做什么? – Oniropolo 2013-05-07 20:42:28

+0

传入的字符串类似于“a * b * c * d”'。当你评估它时,第二个参数是一个本地字典。例如,'{'a':2,'b':3,'c':1,'d':1}'。它告诉python每个变量的值。 – Felipe 2013-05-08 03:56:27

5

也许你真的想要combinations_with_replacement

>>> from itertools import combinations_with_replacement 
>>> a = ['a', 'b', 'c'] 
>>> c = combinations_with_replacement(a, 4) 
>>> for x in c: 
...  print x 
...  
('a', 'a', 'a', 'a') 
('a', 'a', 'a', 'b') 
('a', 'a', 'a', 'c') 
('a', 'a', 'b', 'b') 
('a', 'a', 'b', 'c') 
('a', 'a', 'c', 'c') 
('a', 'b', 'b', 'b') 
('a', 'b', 'b', 'c') 
('a', 'b', 'c', 'c') 
('a', 'c', 'c', 'c') 
('b', 'b', 'b', 'b') 
('b', 'b', 'b', 'c') 
('b', 'b', 'c', 'c') 
('b', 'c', 'c', 'c') 
('c', 'c', 'c', 'c') 

没有关于你如何映射字符串,我不能在你的第二个问题发表评论的数字,不过,自己写product功能或使用numpy的更多信息,并不太难。

+0

我不知道它被称为 “combinations_with_replacement”。对我来说太愚蠢了。非常感谢! – Oniropolo 2013-05-07 15:46:31

+0

不要猜测其他人在所有可能性中称之为什么并不愚蠢。哎呀,在2.7版之前,甚至没有内置的功能来做到这一点!乐意效劳。 – DSM 2013-05-07 15:47:45