【问题标题】:Is there a more elegant way of getting permutations with replacement in python?有没有一种更优雅的方法可以在 python 中通过替换获得排列?
【发布时间】:2022-12-24 01:00:54
【问题描述】:

我目前想要一组元素的所有排列替换。

例子:

elements = ['a', 'b']

permutations with replacement = 

[('a', 'a', 'a'),
 ('a', 'a', 'b'),
 ('a', 'b', 'a'),
 ('a', 'b', 'b'),
 ('b', 'a', 'a'),
 ('b', 'a', 'b'),
 ('b', 'b', 'a'),
 ('b', 'b', 'b')]

到目前为止,我能够做到这一点的唯一方法是使用itertools.product,如下所示:

import itertools as it

sample_space = ['a', 'b']

outcomes = it.product(sample_space, sample_space, sample_space)
list(outcomes)

我只是想知道是否有更好的方法来做到这一点,因为很明显,随着样本空间和所需长度变大,这会变得笨拙且容易出错

期待找到类似itertools.permutations(['a', 'b'], length=3, replace=True) 的东西吗?

我试过 itertools.permutations 但唯一的参数是 iterabler,这是所需的长度。

上述示例使用it.permutations(sample_space, 3) 的输出将是一个空列表[]

【问题讨论】:

  • 你读过product文档了吗?看起来不像你做的。
  • list(itertools.product(sample_space, repeat=3)) 给你你想要的。请注意,repeat 是一个 kwarg。
  • @Samwise 怎么做到的“避免在 cmets 中回答问题”
  • 这是节日奇迹!

标签: python combinations permutation python-itertools discrete-mathematics


【解决方案1】:

如果您使用替换进行抽样,那么根据定义,您得到的不是集合的排列(仅表示“重新排列”)。所以我不会为此寻找 permutations 函数。 product 是对的;例如itertools.product(['a','b'], repeat=3)

请注意,如果您从一个二元组中抽取 N 次放回,那么您实际上已经创建了一个 N 位二进制数,以及随之而来的所有可能性。您刚刚将 0 和 1 换成了 a 和 b。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-24
    • 1970-01-01
    • 2010-11-23
    • 2016-11-15
    • 2020-02-12
    • 1970-01-01
    • 2021-08-14
    相关资源
    最近更新 更多