在不使用 itertools 的情况下生成 Python 中字符串的所有排列

Generate all permutations of a string in Python without using itertools

我需要生成字符串中字符的所有可能排列(重复)。如果字符串是 'abc',输出应该是:

aaa aab aac 美国广播公司 ... 加拿大广播公司 cca 建设银行 ccc

我不会用itertools模块,也不想用递归(因为这只是一个例子,我真正需要的是输出百万个排列和恐怕 运行 内存不足)

我可以这样做:

s = 'abc'

for c1 in range(0, 3):
    for c2 in range(0, 3):
        for c3 in range(0, 3):
            print(s[c1]+s[c2]+s[c3])

基本上,我的 for 循环数与字符串的字符数一样多。 现在假设字符串的长度为 10,例如!

有更好的方法吗?

如果您害怕 运行 内存不足,请使用生成器。继续调用 d.next() 获取您的值。它只对小的嵌套循环有效。

>>> s = 'abc'
>>> d =( (x,y,z) for x in s for y in s for z in s)
>>> d.next()
'aaa'
>>> d.next()
'aab'

如果您想要所有值,只需执行

list(d)

对于任意长度的使用:这会创建与字符串中的元素一样多的组,然后遍历所有这些组并继续添加到最终结果中。这就是 itertools.product 在 python 中的实现方式。有关详细信息,请访问 here

def product(x):
        final = [[]]
        l = len(x)
        groups = [list(x)] * l
        for i in groups:
            final = [x+[y] for x in final for y in i]
        for k in final:
            yield ''.join(k)

强制所有结果:

list(product('abc'))

['aaa',
 'aab',
 'aac',
 'aba',
 'abb',
 'abc',
 'aca',
 'acb',
 'acc',
 'baa',
 'bab',
 'bac',
 'bba',
 'bbb',
 'bbc',
 'bca',
 'bcb',
 'bcc',
 'caa',
 'cab',
 'cac',
 'cba',
 'cbb',
 'cbc',
 'cca',
 'ccb',
 'ccc']

解决此问题的一种简单方法是将字符串中的字符视为不寻常数字系统中的数字。字符串的长度是基数。因此 'abc' 的排列(重复)对应于基数 3 中从 03**3-1 的数字,其中 'a' 是数字 0'b'1'c'2.

def permutations_with_repetition(s):
    base = len(s)
    for n in range(base**base):
        yield "".join(s[n // base**(base-d-1) % base] for d in range(base))

样本运行:

>>> for p in permutations_with_repetition("abc"):
    print(p)


aaa
aab
aac
aba
abb
abc
aca
acb
acc
baa
bab
bac
bba
bbb
bbc
bca
bcb
bcc
caa
cab
cac
cba
cbb
cbc
cca
ccb
ccc

如果您被允许使用 itertools,您会希望 itertools.product 带有 repeat 关键字参数:itertools.product("abc", repeat=3)