【问题标题】:Combinations with repetition in python, where order MATTERSpython中重复的组合,其中顺序很重要
【发布时间】:2016-06-19 18:10:06
【问题描述】:

来自 python 的文档:https://docs.python.org/2/library/itertools.html#itertools.combinations

查看combinations_with_replacement:“#combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC”

我想使用相同的功能,并生成“BA”、“CA”和“CB”。

【问题讨论】:

  • 所以排列而不是组合?
  • 排列不会返回 AA、BB 或 CC。需要itertools.product('ABC', repeat=2)

标签: python combinations itertools combinatorics cartesian-product


【解决方案1】:

itertools.product 绝对是您在这里寻找的方法。正如文档所述,它实际上是一个紧凑的 for 循环; product(A,B) 等价于((x, y) for x in A for y in B)

product 将返回它可以返回的每个元素组合,特定于订单,因此product('ABC', 'DEF', 'GHI') 将获得ADG, ADH, ADI, AEG [...] CFI。如果要包含重复,请设置可选的 repeat 变量。 product(A, repeat=4) 等价于 product(A,A,A,A)。同样,product(A, B, repeat=3)product(A,B,A,B,A,B) 相同。

简而言之:要获得您正在寻找的结果,请致电itertools.product('ABC', repeat=2)。这将按顺序为您提供元组 AA, AB, AC, BA, BB, BC, CA, CB, CC

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-14
    • 2021-10-12
    • 2012-09-28
    • 1970-01-01
    • 2016-11-03
    • 2018-04-25
    相关资源
    最近更新 更多