如何在python中生成所有可能的字符串?

如何在python中生成所有可能的字符串?,python,python-2.7,iterator,Python,Python 2.7,Iterator,我的目标是能够生成所有可能的长度为x的字符串(字母和数字),并能够为每个字符串激活一块代码。(就像迭代器一样)唯一的问题是itertools中的那些不能复制相同字符串中的字母。例如: 我得到的是“ABC”“BAC”“CAB”等,而不是“AAA” 有什么建议吗?使用: 请注意,对于较长的字符串,创建包含所有组合的列表是非常低效的-请迭代它们: for string in itertools.imap(''.join, itertools.product('ABC', repeat=3)):

我的目标是能够生成所有可能的长度为x的字符串(字母和数字),并能够为每个字符串激活一块代码。(就像迭代器一样)唯一的问题是itertools中的那些不能复制相同字符串中的字母。例如:

我得到的是“ABC”“BAC”“CAB”等,而不是“AAA”

有什么建议吗?

使用:

请注意,对于较长的字符串,创建包含所有组合的列表是非常低效的-请迭代它们:

for string in itertools.imap(''.join, itertools.product('ABC', repeat=3)):
    print string
要获取所有字符和数字,请使用
string.uppercase+string.lowercase+string.digits

如果希望字母重复,请使用:

>>> from itertools import product
>>> from string import ascii_uppercase
>>> for combo in product(ascii_uppercase, repeat=3):
...     print ''.join(combo)
...
AAA
AAB
...
ZZY
ZZZ

itertools.compositions()
itertools.permutations()
不是适合您工作的正确工具。

Python 3已更改,因此内置的
map
现在返回迭代器。第二个建议是使用
itertools.imap
,除非您的python版本<3.0。
>>> from itertools import product
>>> from string import ascii_uppercase
>>> for combo in product(ascii_uppercase, repeat=3):
...     print ''.join(combo)
...
AAA
AAB
...
ZZY
ZZZ