给定一个数组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..]
Run Code Online (Sandbox Code Playgroud)
下面如何在Python中生成列表的所有排列,我试过:
print list(itertools.permutations(['a', 'b' , 'c'], 4))
[]
print list(itertools.product(['a', 'b' , 'c'], repeat=4)
Run Code Online (Sandbox Code Playgroud)
但是我得到了重复的笛卡尔积.例如,列表将包含两者['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
Run Code Online (Sandbox Code Playgroud)
在python中执行此操作的最快方法是什么?用numpy做它会有可能/更快吗?谢谢!
也许你真的想要combination_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')
Run Code Online (Sandbox Code Playgroud)
如果没有关于如何将字符串映射到数字的更多信息,我无法对第二个问题发表评论,但编写自己的product函数或使用函数numpy并不太困难.
Fel*_*ipe -1
编辑:不要使用这个;使用其他答案
combos = combinations_with_replacement(a, 4)
product_strings = ['*'.join(c) for c in combos]
products = [eval(s, globals(), values) for s in product_strings]
Run Code Online (Sandbox Code Playgroud)
不用说,要非常小心eval。仅当您要创建列表时才使用此解决方案a。
漏洞利用示例:a = ['from os import', '; system("rm -rf .");']