python 与替换的组合未按预期工作

python combination with replacement not working as expected

我想通过使用一组允许的替换字符来生成特定长度的所有组合:

我认为 itertools.combinations_with_replacement 是我需要的。所以这就是我所做的:

from itertools import combinations_with_replacement
allowed = ['0', '1', '8', '6', '9']
comb = list(combinations_with_replacement(allowed,2))

然而这样产生的组合数是15。但应该是25(5^2)。怎么回事?

编辑:

我按照@Michael Bianconi 的建议用 permutations 替换了 combinations_with_replacement 但它也不起作用 - 我得到的结果集是 20,而不是 25。

00, 01, 08, 06, 09
11, 18, 16, 19
88, 86, 89
66, 69
99

有 15 种可能的组合。

您可能搜索的产品是:

import itertools
allowed = ['0', '1', '8', '6', '9']
product = list(itertools.product(allowed, repeat=2))
print(len(product))

25

字符串在 Python 中是可迭代的,因此您可以使用:

import itertools
for result in itertools.product('01869', repeat=2)):
    print(result)