我可以用 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)]
你正在寻找一个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)]
另请参阅较早的帖子中对此问题的更多答案。
Nakor 得到了正确的答案:
product([1,2,3], repeat=2)
我错误地尝试:
list(product([1,2,3],2))
哪些错误:
TypeError: 'int' object is not iterable