如何在python中生成所有可能的字符串? [英] How to generate all possible strings in python?

查看:315
本文介绍了如何在python中生成所有可能的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My goal is to be able to generate all possible strings (Letters and numbers) of length x and be able to activate a block of code for each one. (like an iterator) The only problem is the ones in the itertools don't make copies of the letter in the same string. For example:

我得到ABCBACCAB等而不是AAA。

I get "ABC" "BAC" "CAB" etc. instead of "AAA".

有什么建议吗?

推荐答案

使用 itertools.product()

>>> import itertools
>>> map(''.join, itertools.product('ABC', repeat=3))
['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']

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

Note that creating a list containing all combinations is very inefficient for longer strings - iterate over them instead:

for string in itertools.imap(''.join, itertools.product('ABC', repeat=3)):
    print string

要获取所有字符和数字,请使用 string.uppercase + string.lowercase + string.digits

To get all characters and numbers use string.uppercase + string.lowercase + string.digits.

这篇关于如何在python中生成所有可能的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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