【问题标题】:List every permutations of iterable [duplicate]列出可迭代的每个排列[重复]
【发布时间】:2017-06-03 11:31:27
【问题描述】:
from itertools import permutations
l = [0, 1, 2, 3, 4]
x = permutations (l, 3)

我得到以下信息:

(0, 1, 2) , (0, 1, 3), ...., (0, 2, 1), (0, 2, 3), (0,2,4),...., (4, 3, 0), (4, 3, 1),
(4, 3, 2)

这是预期的。 但我需要的是:

(0, 0, 0), (0, 0, 1), ...., (0, 0, 4), (0, 1, 0), (0, 1, 1)........

如何做到这一点?

【问题讨论】:

  • 你没有解释结果应该包含什么。但请检查 itertools 中的其他功能,看看是否适合您的需求。

标签: python permutation


【解决方案1】:

您需要的是一个置换替换,或者一个产品,但itertoolpermutations 产生置换而不替换。您可以自己计算产品:

[(x,y,z) for x in l for y in l for z in l]
#[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 0, 4), (0, 1, 0), ...

或者使用itertools中的同名函数:

list(itertools.product(l,repeat=3))
# [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 0, 4), (0, 1, 0),...

后一种方法效率更高。

【讨论】:

    【解决方案2】:

    您需要使用 product ,而不是使用 permutations,来自 itertools 模块,如下例所示:

    from itertools import product
    
    l = [0, 1, 2, 3, 4]
    # Or:
    # b = list(product(l, repeat=3))
    b = list(product(l,l,l))
    print(b)
    

    输出:

    [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), ..., (4, 4, 1), (4, 4, 2), (4, 4, 3), (4, 4, 4)]
    

    【讨论】:

      【解决方案3】:

      你需要产品而不是排列

      from itertools import product
      l = [0, 1, 2, 3, 4]
      b = list(product(l, repeat=3))
      

      【讨论】:

        猜你喜欢
        • 2018-01-29
        • 2015-12-25
        • 2015-01-17
        • 2023-03-23
        • 1970-01-01
        • 2019-01-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多