列表的笛卡尔积,无重复项 [英] Cartesian products of lists without duplicates

查看:176
本文介绍了列表的笛卡尔积,无重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个数组a=['a','b','c'],您将如何返回没有重复项的数组的笛卡尔积.示例:

Given an array a=['a','b','c'], how would you go about returning the Cartesian product of the array without duplicates. Example:

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

遵循>如何生成列表的所有排列在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'],它们显然是相等的.

But I get the Cartesian product with duplicates. For example the list will contain both ['a','a','b','b'] and ['a','b','b','a'] which are clearly the equal.

注意:我的'a','b','c'是存储数字的变量,例如1,2,3.因此,在获得字母组合列表之后,我需要:

Note: my 'a','b','c' are variables which store numbers say 1,2,3. So after getting the list of combinations of the letters, I would need to: say,

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

在python中最快的方法是什么?使用numpy可以/更快吗? 谢谢!

What is the fastest way of doing this in python? Would it be possible/faster to do it with numpy?? Thanks!

推荐答案

如果保证原始集具有唯一性,则combinations_with_replacement解决方案将起作用.如果没有,您可以先将其通过set()传递给唯一变量.对于产品,假设您将值存储在字典values中,并且所有变量都是有效的python标识符,则可以执行以下操作

If your original set is guaranteed uniqueness, then the combinations_with_replacement solution will work. If not, you can first pass it through set() to get it down to unique variables. Regarding the product, assuming you have the values stored in a dictionary values and that all the variables are valid python identifiers, you can do something like the following

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时使用此解决方案.

Needless to say, be very careful with eval. Only use this solution if you are creating the list a.

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

这篇关于列表的笛卡尔积,无重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆