【问题标题】:Python: Generate String Combinations with set count of type. (String of x length with, x numbers, x uppercase, x lowercase)Python:生成具有集合类型计数的字符串组合。 (x长度的字符串,x数字,x大写,x小写)
【发布时间】:2020-07-21 13:43:02
【问题描述】:

寻找使用限定符生成字符串组合的最有效方法,

长度为 16 的字符串,有 2 个数字,8 个小写,6 个大写,一种遍历所有组合的方式。

也许使用 itertools.filterfalse 或 itertools.dropwhile?

【问题讨论】:

  • 抱歉,已编辑问题。
  • 看看 Riccardo Bucco 当前的答案,它应该可以解决问题

标签: python string passwords combinations itertools


【解决方案1】:

这是一个可能的解决方案:

from itertools import combinations_with_replacement, permutations, product
from string import ascii_digits, ascii_lowercase, ascii_uppercase
from sympy.utilities.iterables import multiset_permutations

def generator():
    n_gen = combinations_with_replacement(ascii_digits, 2)
    l_gen = combinations_with_replacement(ascii_lowercase, 8)
    u_gen = combinations_with_replacement(ascii_uppercase, 6)
    for numbers, lowercase, uppercase in product(n_gen, l_gen, u_gen):
        for p in multiset_permutations(numbers + lowercase + uppercase):
            yield ''.join(p)

示例(打印 100 个字符串):

g = generator()
i = 0

for s in g:
    if i > 100:
        break
    print(s)
    i += 1

当然不要全部打印出来,太多了!!确实有超过 10^26 个可能的字符串!除非您知道自己在做什么,否则不要与他们一起创建列表。

【讨论】:

  • 注意:组合是没有替换的,所以你永远不会生成超过 1 个a 的字符串。但是使用替换会使普通排列不能很好地工作,因为它会多次产生一些排列。
  • @Adam.Er8 真的!感谢您的贡献!你知道任何解决方法吗?
  • 我唯一能想到的是使用combinations_with_replacement,然后使用set 来避免重复排列,这将占用大量内存
  • @Adam.Er8 是的,这绝对不可能......好吧,我会尝试考虑其他事情
  • 太棒了!有人应该建议在itertools 中添加这样的功能:P
【解决方案2】:

在线查看源码here

import random
import string

def get_random_alphanumeric_string(length):
    letters_and_digits = string.ascii_letters + string.digits
    result_str = ''.join((random.choice(letters_and_digits) for i in range(length)))
    print("Random alphanumeric String is:", result_str)

get_random_alphanumeric_string(8)
get_random_alphanumeric_string(8)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多