【问题标题】:Generate combinations of length k from number set N, order matters, replacement allowed从数字集 N 生成长度 k 的组合,顺序很重要,允许替换
【发布时间】:2017-03-06 13:30:23
【问题描述】:

我想从一组 N 个数字中生成长度为 k 的组合,其中顺序很重要,数字可以替换。例如,如果 k = 3,并且 N = [1, 2, 3],则候选输出将包括 (1, 1, 1), (2, 2, 2), (3, 2, 1) , (1, 2, 3)。

下面的代码我相信我快到了

x = list(itertools.combinations_with_replacement(range(1,4),3)

但这给出了顺序无关紧要的结果 - 即它认为 (1, 2, 3) 与 (3, 2, 1), (2, 3, 1) 等相同。

非常感谢任何帮助!

【问题讨论】:

  • 你在乎有两倍的输出吗?你需要它是随机的吗?
  • 排列不重复元素。
  • 听起来你想要笛卡尔积。

标签: python combinations permutation combinatorics itertools


【解决方案1】:

你需要的是product

import itertools

N = [1, 2, 3]

y = list(itertools.product(N, N))
print(y)  # [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
          #             ^               ^
          #             |_______________| he no longer thinks it's the same

现在,从你的问题来看,如果k != len(N) 不清楚你想做什么,所以我会把它留给你(切片N 可能吗?)..

【讨论】:

    【解决方案2】:

    试试这个:

    import itertools
    x = [1, 2, 3]
    list(itertools.product(x, repeat=3))
    

    【讨论】:

    • 只是把它放在一个列表中。使用 list(itertools.product(x, repeat=3)) 可能会更好,现在编辑它
    • 在最新版本的 Python 中,您可以使用 [*itertools.product(x, repeat=3)]
    猜你喜欢
    • 2023-03-12
    • 2019-07-13
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    相关资源
    最近更新 更多