【问题标题】:generating all permutations with all orderings and replacements in Python [duplicate]在Python中生成具有所有排序和替换的所有排列[重复]
【发布时间】:2020-03-27 08:37:07
【问题描述】:

如何生成列表中一组元素的所有可能排序:

  1. 生成所有排序(不仅仅是那些排序好的)
  2. 允许重复

我知道使用itertools.permutations(iterable[, r]) 我可以做到以下几点:

import itertools

a = itertools.permutations([1,2])
list(a)

输出:

[(1, 2), (2, 1)]

也使用itertools.combinations_with_replacement(iterable, r):

import itertools

a = itertools.combinations_with_replacement([1,2],2)
list(a)

输出:

[(1, 1), (1, 2), (2, 2)]

但我想要的是function,它执行以下操作:

a = function([1,2],2)

输出:

[(1, 1), (1, 2), (2, 1), (2, 2)]

换句话说,对于具有不同元素的大小为 n 的列表和给定的 r 输入,它可以生成所有可能的 n**r 可能的组合

【问题讨论】:

    标签: python


    【解决方案1】:

    itertools.product([1,2],repeat=2)

    我觉得……

    【讨论】:

    • 是的,成功了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多