【问题标题】:Permutations with repetitions?重复排列?
【发布时间】:2020-02-02 03:25:17
【问题描述】:

我可以用 itertools 做到这一点:

list(permutations([1,2,3],2))
: [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

但我也如何生成:

 (1,1),(2,2),(3,3)

当然不用单独做:[(i,i) for i in range(4)]

【问题讨论】:

  • product([1,2,3], repeat=2) 也使用 itertools 怎么样?
  • ooo.. 我明白了..我试过 product([1,2,3], 2) ;)
  • TypeError: 'int' 对象不可迭代

标签: python repeat itertools permute


【解决方案1】:

添加到 Nakor 的评论中,看起来您想要的是 cartesian product。您可以通过list(itertools.product([1,2,3],repeat=2)) 获得。

Permutations 另一方面,根据文档

permutations() 的代码也可以表示为 product() 的子序列,过滤以排除具有重复元素的条目(来自输入池中相同位置的条目)

所以看起来没有办法使用list(itertools.permutations([1,2,3],2)) 并在不使用额外逻辑的情况下获得所需的输出。

【讨论】:

  • @sten:这是你想要的吗?
  • 这是一个:product([1,2,3], repeat=2)
【解决方案2】:

您正在寻找permutations_with_replacement 工具。

这将给出n**r results,例如3**2 = 9 个总结果。

Python 还没有实现这个工具;原因不明。然而,排列通常可以用笛卡尔积来实现。

代码

修改自docs:

def permutations_with_replacement(iter_, r=None):
    """Yield all or some permutations from a replenished pool; from docs."""
    pool = tuple(iter_)
    n = len(pool)
    r = n if r is None else r

    for indices in itertools.product(range(n), repeat=r):
        #if len(set(indices)) == r:
            #print(indices)

        yield tuple(pool[i] for i in indices)

演示

results = list(permutations_with_replacement([1, 2, 3], r=2))
len(results)
# 9

results
# [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

等价于:

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

另请参阅earlier post 对此问题的更多答案。

【讨论】:

    【解决方案3】:

    Nakor 得到了正确答案:

      product([1,2,3], repeat=2)
    

    我试错了:

     list(product([1,2,3],2))
    

    哪些错误:

      TypeError: 'int' object is not iterable
    

    【讨论】:

      猜你喜欢
      • 2019-09-18
      • 2012-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多