简体   繁体   English

生成n个集合的笛卡尔积

[英]generate cartesian product of n sets

How to generate permutations of n variables given the domain of each variable. 给定每个变量的域,如何生成n个变量的排列。 (in python) (在python中)

I know about itertools, but that requires a fixed domain for the permutations so that won't work. 我知道itertools,但是需要固定的排列范围,这样才能使用。 Also is there a python library that does this? 还有一个python库可以做到这一点吗? Thanks. 谢谢。

Basically: Given 3 variables: A with Domain (2,3) B with Domain (1) C with Domain (1,2,3) 基本上:给定3个变量:A具有域(2,3)B具有域(1)C具有域(1,2,3)

How do you generate all permutations of ABC? 您如何生成ABC的所有排列?

2,1,1
3,1,1
2,1,2
3,1,2
2,1,3
3,1,3
>>> list(itertools.product((2, 3), (1,), (1, 2, 3)))
[(2, 1, 1), (2, 1, 2), (2, 1, 3), (3, 1, 1), (3, 1, 2), (3, 1, 3)]

The itertools.product function does not require "fixed domain" as you state, nor do any functions. 您声明的itertools.product函数不需要“固定域”,也不需要任何函数。

For example this code does what you want: 例如,此代码可以执行您想要的操作:

a = [2, 3]
b = [1]
c = [1, 2, 3]
print(itertools.product(a, b, c))

and would do the same for any set of sequences of any length. 并对任何长度的序列集执行相同的操作。

itertools.product has been duly suggested and works fine for the problem at hand. itertools.product已被适当建议,并且可以很好地解决当前的问题。 If you are - if only for academic reasons - interested in a sample implementation, here's a generator function: 如果您只是出于学术原因而对示例实现感兴趣,那么这里有一个生成器函数:

def cartesian_product(*lists):  # lists can really be any sequences
    if any([not l for l in lists]):  # c.p. is empty if any list is empty
        return

    n = len(lists)
    indexes = [0] * n

    while True:
        yield tuple(lists[i][indexes[i]] for i in xrange(n))  # currently indexed element of each list
        # update indexes
        for i in xrange(n-1, -1, -1):  # loop through indexes from back
            if indexes[i] < len(lists[i]) - 1:      # stop at first index that can be incremented ...
                indexes[i] += 1                     # ... increment it ...
                indexes[i+1:n] = [0] * (n - i - 1)  # ... reset all succeeding indexes to 0
                break
        else:  # no index could be incremented -> end
            break

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM