列表的笛卡尔积,无重复项

编程入门 行业动态 更新时间:2024-10-25 08:16:27
本文介绍了列表的笛卡尔积,无重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给出一个数组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 .");']

更多推荐

列表的笛卡尔积,无重复项

本文发布于:2023-11-30 12:05:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649886.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:笛卡尔   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!