如何使python脚本生成python中特定字符集的所有可能组合?

myzjeezk  于 2023-03-24  发布在  Python
关注(0)|答案(3)|浏览(353)

我需要一个代码,可以生成所有可能的字母组合。它需要是一个生成器函数,生成所有组合,并使用yield函数将它们返回到前面的调用。它只需要接受一个值:length,指定新生成的脚本的长度。
这是我到目前为止得到的:

characters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", "{", "}", "[", "]", "|", "\\", ":", ";", '"', "'", "<", ">", ".", "/", "?"]

def combo(length)
    #Future combo generation code
    yield combos
    return

运行print(combo(2))所需的输出,例如:

['aa', 'ab', 'ac', 'ad', 'ae', 'af', 'ag', ...]

此代码将需要生成多达20个字符组合。

izkcnapc

izkcnapc1#

这对你的目的起作用。

import itertools

def generate_combinations(list_of_characters):
    for i in range(1, len(list_of_characters)+1):
        for j in itertools.combinations(list_of_characters, i):
            print(j)

generate_combinations(['a', 'b', 'c', 'd'])

只要将函数中的列表更改为您的列表,它就可以工作了。

8wtpewkr

8wtpewkr2#

我希望这能回答你的问题。

import string
import random

def combo(length):
    code = random.choices(string.ascii_letters + string.punctuation, k=length)
    yield code
    
code = combo(20)
print(code)
print(*code)

结果

<generator object combo at 0x7fc78cef3ba0>
['r', 'N', '>', 'G', 'j', 'F', 'E', ')', 'C', '^', ':', 'z', 'q', 'o', '^', 'T', 'y', 's', 'y', '#']

请在此处查看所使用的模块:https://docs.python.org/3/library/random.html#functions-for-sequenceshttps://docs.python.org/3/library/string.html#module-string

g6ll5ycj

g6ll5ycj3#

可能有用

characters_for_combinations   = [ "a", "b", "c"]
from itertools import permutations
print(list(permutations(characters_for_combinations  )))

相关问题