2017-09-25 66 views
-2

我正在製作一個程序,運行時會根據我定義的字符列表生成一個隨機字符串。 的代碼是:Python字符串生成器,按照特定的順序

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?要做到這一點

+0

你想它使用Upperletters,Lowerletters,符號和數字的順序,他們是在陣列中或做你想讓它先用Upperletters,然後用Lowerletters,然後用符號和最後使用數字? – kyle

+1

您的導入是冗餘/不一致的。爲什麼不下定決心? –

+0

您能舉出電流輸出和期望輸出的例子嗎? – Neo

回答

-2

編輯FIXED IT 我只是一年前開始編碼,並有從來沒有使用過排序,所以我沒有打擾它。我改了一下你的代碼。我刪除了Shuffle,因爲爲什麼你應該隨機從混洗列表中挑選一些東西?這與從排序的隨機選取相同! Full code

def shuffle(): 
    randomlength = randint(8, 12) 
    pre = {0: '', 1:'',2:'',3:''} 
    lists = {0: Upperletters, 1: Lowerletters, 2: Symbols, 3: Numbers} 
    for x in range(4): pre[x]+=(choice(lists[x])) 
    for i in range(randomlength-4): 
     x = randint(1, 74) 
     if x < 27: pre[0]+=choice(lists[0]) 
     elif x < 53: pre[1]+=choice(lists[1]) 
     elif x < 65: pre[2]+=choice(lists[2]) 
     else: pre[3]+=choice(lists[3]) 
    pw = '' 
    for v in pre.values(): 
      pw += v 
    return pw 
print(shuffle()) 
+0

雖然你改變了概率分佈。例如,你的數字比他們的可能性要大得多。 –

+0

@StefanPochmann呃不,我不是這樣,對於這四種類型中的每一種都有25%的機率 –

+1

是的。究竟。每個25%。它本來不是。 –

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)) 
+0

我發現名稱「選項」稍有混淆,將其稱爲「選項」。 –

+0

不錯的解決方案!我會將「權重」重命名爲「category_index」。 – user4815162342

+0

好吧,我會在解決緩存失效後找出一些更好的名字 – wim

相關問題