我如何才能找到一组数组元素的所有组合?组合、数组、元素

2023-09-11 06:43:34 作者:甜御

我简化更大,更复杂的问题,下面...

由于三个整数的数组,什么是最有效的方式来回报每一个元件的所有可能的组合?需要注意的是,从每个阵列中的每个值将始终在同一位置被赋予这样 [A,B,C] 将是一样的 [C, B,A] 。我期望的结果是用含有一个单一组合每个散列数组的数组。例如:

由于:

  VAR ARRAY1 = [1,2]
变种ARRAY2 = [A,B]
VAR ARRAY3 = [FOO,巴]
 

其结果将是:

  [
  [1,一,富]
  [2,一,FOO]
  [1,B,FOO]
  [2,B,FOO]
  [1,一,巴],
  [2,一,吧]
  [1,B栏]
  [2,B,巴]
]
 

解决方案 在asp中有一个数组,数组里面的元素都是如下所示

在Python中,使用的 itertools.product :

  itertools.product(ARRAY1,ARRAY2,ARRAY3)
 

和它包装在一个列表如果你需要一个序列,而不仅仅是一个迭代。

如果你想看看它是如何做,这是相当于$ C $在 itertools 文档给出C:

 高清产品(*的args,** kwds):
    #产品('ABCD','XY') - >斧好哦Bx的通过CX赛扬霉素镝
    #产物(范围(2),重复= 3) - > 000 001 010 011 100 101 110 111
    池=图(元组,参数)* kwds.get('重复',1)
    结果= [[]]
    在池池:
        结果= [X +的结果Y]对于x y的池]
    为督促的结果:
        产量元组(PROD)
 

虽然该版本的code不是特别有效的。

也有在 PyPy版本的Python实现的itertools 。

I'm simplifying a larger complex problem with the following...

Given three arrays of integers, what's the most efficient way to return all the possible combinations of each of the elements? Note that each value from each array will always be given in the same position so [A,B,C] would be the same as [C,B,A]. My desired result is an array of arrays with each hash containing a single combination. For example:

Given:

var array1 = [1,2]
var array2 = [a,b]
var array3 = [foo,bar]

The result would be:

[
  [1,a,foo],
  [2,a,foo],
  [1,b,foo],
  [2,b,foo],
  [1,a,bar],
  [2,a,bar],
  [1,b,bar],
  [2,b,bar]
]

解决方案

In Python, use itertools.product:

itertools.product(array1, array2, array3)

and wrap it in a list if you need a sequence, not just an iterable.

If you want to see how it's done, this is the "equivalent" code given in the itertools docs:

def product(*args, **kwds):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

although that version of the code isn't particularly efficient.

There is also a Python implementation in the PyPy version of itertools.