Python字符串生成器,按特定顺序

时间:2017-09-25 21:32:21

标签: python python-3.x

我制作一个程序,运行时会从我定义的字符列表中生成一个随机字符串。 代码是:

from random import randint
from random import *
import random
Upperletters=["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"]
Lowerletters = ["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"]
Symbols = ["!","$","%","^","&","*","(",")","_","-","+","="]
Numbers = ["1","2","3","4","5","6","7","8","9","0"]
random.shuffle(Symbols)
random.shuffle(Numbers)
random.shuffle(Upperletters)
random.shuffle(Lowerletters)
randomlength = randint(8, 12)
stringgenerator = ''.join(choice(Upperletters + Symbols + Numbers + 
Lowerletters) for x in range(randomlength))
print(stringgenerator)
stringgeneratorlower = stringgenerator.lower()
letter_combos = ["qwe","wer","ert","rty","tyu","yui","uio","iop","asd","sdf","dfg","fgh","ghj","hjk","jkl","zxc","xcv","cvb","vbn","bnm"]
keyboard =int(sum(stringgeneratorlower.count(fragment) for fragment in letter_combos))
if keyboard >= 1:
    print("Bad try again")

但我的问题是我希望字符串按照它们添加的顺序使用符号,所以它应该首先是大写字符,然后是一些符号,然后是一些数字,然后是小写。我的问题是,它以完全随机的顺序生成它们。如何按照我想要的顺序生成它们,以便生成的字符串不包含列表中的任何letter_combos?

2 个答案:

答案 0 :(得分:1)

一种方法是为每个类别分配权重,然后按这些权重对生成的字符串进行排序:

import string
from random import choice, randint

symbols = '!$%^&*()_-+='

categories = [
    string.ascii_uppercase,
    symbols,
    string.digits,
    string.ascii_lowercase,
]
choices = ''.join(categories)
weights = {char: n for n, chars in enumerate(categories) for char in chars}

length = randint(8, 12)
rand_unordered = [choice(choices) for _ in range(length)]
rand_ordered = ''.join(sorted(rand_unordered, key=weights.get))

答案 1 :(得分:-2)

编辑固定 我一年前才开始编码,从未使用过排序,所以我没有打扰它。我稍微改了你的代码。我删除了Shuffle,因为你为什么要从一个洗牌列表中随机选择一些东西?这与从有序的一个中随机挑选相同! Full code

Android.mk