哪个itertools生成器不跳过任何组合?
发布于 2021-01-29 15:03:18
当我运行此代码时,我没有得到3个字符的所有可能组合:
def comb(iterable, r):
pool = tuple(iterable)
n = len(pool)
for indices in permutations(range(n), r):
if sorted(indices) == list(indices):
yield tuple(pool[i] for i in indices)
def start():
for x in comb("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12234567890!@#$%^&*?,()-=+[]/;",3):
print x
相反,它跳过了一些。当我重复字符3次时,我得到了所需的所有组合,但又得到了多次。这花费了三倍的时间,这不是我想要的。我将要计算数百万种组合,因此我需要知道一种替代重复字符的方法。
关注者
0
被浏览
55
1 个回答
-
您正在寻找
itertools.product(characters, repeat = 3)
。参见
itertools.product
文档。>>> ' '.join(''.join(x) for x in itertools.product('abcd', repeat = 2)) aa ab ac ad ba bb bc bd ca cb cc cd da db dc dd