生成n个集合的笛卡尔积

2024-09-30 14:24:19 发布

您现在位置:Python中文网/ 问答频道 /正文

如何生成给定每个变量域的n个变量的排列。(在python中)

我知道itertools,但这需要一个固定的域来进行置换,这样就行不通了。还有一个python库可以做到这一点吗?谢谢。在

基本上: 给定3个变量: 带域(2,3)的A B带域(1) 带域(1,2,3)的C

如何生成ABC的所有排列?在

2,1,1
3,1,1
2,1,2
3,1,2
2,1,3
3,1,3

Tags: abcitertools带域
3条回答

itertools.product函数不需要您所说的“固定域”,也不需要任何函数。在

例如,此代码执行您想要的操作:

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

对任何长度的序列都是一样的。在

>>> 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)]

itertools.product已经得到了适当的建议,并且对于当前的问题工作得很好。如果您(如果只是出于学术原因)对示例实现感兴趣,下面是一个生成器函数:

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

相关问题 更多 >