1

我可以用 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)]

4

3 回答 3

3

添加到 Nakor 的评论中,看起来您想要的是笛卡尔积。你可以用list(itertools.product([1,2,3],repeat=2)).

另一方面,根据文档,排列

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

所以看起来没有办法使用list(itertools.permutations([1,2,3],2))和获得你想要的输出而不使用额外的逻辑。

于 2019-10-03T19:32:23.860 回答
1

你正在寻找一个permutations_with_replacement工具。

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

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

代码

文档修改:

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)]

另请参阅较早的帖子中对此问题的更多答案。

于 2019-10-05T01:07:40.190 回答
0

Nakor 得到了正确的答案:

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

我错误地尝试:

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

哪些错误:

  TypeError: 'int' object is not iterable
于 2019-10-03T20:51:39.350 回答