代码之家  ›  专栏  ›  技术社区  ›  Eugene

在python中设置产品

  •  7
  • Eugene  · 技术社区  · 16 年前

    一个集合s的n个副本的乘积表示为s。 n . 例如,0,1 三 是所有3位序列的集合:

    {0,1} 三 =(0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0),(1,1,1)

    在python中复制这个想法最简单的方法是什么?

    4 回复  |  直到 16 年前
        1
  •  11
  •   Mark Byers    16 年前

    在python 2.6或更新版本中,可以使用 itertools.product 带可选参数 repeat :

    >>> from itertools import product
    >>> s1 = set((0, 1))
    >>> set(product(s1, repeat = 3))
    

    对于旧版本的python,可以实现 product 使用文档中的代码:

    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)
    
        2
  •  1
  •   Eugene    16 年前

    我想这行吗?

    >>> s1 = set((0,1))
    >>> set(itertools.product(s1,s1,s1))
    set([(0, 1, 1), (1, 1, 0), (1, 0, 0), (0, 0, 1), (1, 0, 1), (0, 0, 0), (0, 1, 0), (1, 1, 1)])
    
        3
  •  1
  •   Eugene    16 年前

    马克,好主意。

    >>> def set_product(the_set, n):
        return set(itertools.product(the_set, repeat=n))
    
    >>> s2 = set((0,1,2))
    >>> set_product(s2, 3)
    set([(0, 1, 1), (0, 1, 2), (1, 0, 1), (0, 2, 1), (2, 2, 0), (0, 2, 0), (0, 2, 2), (1, 0, 0), (2, 0, 1), (1, 2, 0), (2, 0, 0), (1, 2, 1), (0, 0, 2), (2, 2, 2), (1, 2, 2), (2, 0, 2), (0, 0, 1), (0, 0, 0), (2, 1, 2), (1, 1, 1), (0, 1, 0), (1, 1, 0), (2, 1, 0), (2, 2, 1), (2, 1, 1), (1, 1, 2), (1, 0, 2)])
    

    您还可以扩展集合类型并使 __pow__ 方法做到这一点。

        4
  •  0
  •   Tony Veijalainen    16 年前
    print 'You can do like this with generator:'
    print set((a,b,c) for a in s1 for b in s1 for c in s1)