【问题标题】:Permutation with redundant overlaps? Python具有冗余重叠的排列? Python
【发布时间】:2013-08-12 16:06:53
【问题描述】:

我使用 itertools 在我拥有的列表上运行排列。

mylist = [a, b, c, d, e, f]
mypermutations = itertools.permutations(mylist,2)    
mypermutations_list = list(mypermutations) 
print mypermutations_list

打印:

[(a, b), (a, c), (a, d)...]

但是,排列列表不包括(a, a), (b, b), 等。我知道这可能是因为大多数人不想要这种冗余配对。但是,我想包含这样的配对作为我正在编写的程序的控件。

有没有办法运行排列并获得这些组合?我不知道用什么代替排列。

【问题讨论】:

    标签: python permutation


    【解决方案1】:

    你想要itertools.product

    >>> import itertools
    >>> mylist = ['a', 'b', 'c', 'd', 'e', 'f']
    >>> list(itertools.product(mylist, repeat=2))
    [('a', 'a'), ('a', 'b'), ('a', 'c'), ...]
    

    【讨论】:

      【解决方案2】:

      您正在寻找itertools.product,它返回可迭代的笛卡尔积:

      >>> from itertools import product
      >>> list(product('abcdef', repeat=2))
      [('a', 'a'), ('a', 'b'), ('a', 'c'), ('a', 'd'), ('a', 'e'), ('a', 'f'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('b', 'd'), ('b', 'e'), ('b', 'f'), ('c', 'a'), ('c', 'b'), ('c', 'c'), ('c', 'd'), ('c', 'e'), ('c', 'f'), ('d', 'a'), ('d', 'b'), ('d', 'c'), ('d', 'd'), ('d', 'e'), ('d', 'f'), ('e', 'a'), ('e', 'b'), ('e', 'c'), ('e', 'd'), ('e', 'e'), ('e', 'f'), ('f', 'a'), ('f', 'b'), ('f', 'c'), ('f', 'd'), ('f', 'e'), ('f', 'f')]
      

      【讨论】:

        猜你喜欢
        • 2021-09-20
        • 2019-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-20
        • 2011-10-18
        • 1970-01-01
        相关资源
        最近更新 更多