哪个itertools生成器不跳过任何组合? [英] Which itertools generator doesn't skip any combinations?

查看:74
本文介绍了哪个itertools生成器不跳过任何组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行此代码时,我没有得到3个字符的所有可能组合:

When I run this code I don't get all the possible combinations of 3 characters:

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次时,我得到了所需的所有组合,但又得到了多次.这花费了三倍的时间,这不是我想要的.我将要计算数百万种组合,因此我需要知道一种替代重复字符的方法.

Instead it skips some. When I repeated the characters 3 times, I got all the combinations I needed, but I get some multiple times. This takes triple the time and isn't what I want. I'm going to be calculating millions of of combinations so I need to to know an alternative to repeating the characters.

推荐答案

您正在寻找itertools.product(characters, repeat = 3).

请参见 itertools.product 文档.

See the itertools.product docs.

>>> ' '.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

这篇关于哪个itertools生成器不跳过任何组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆