简体   繁体   English

Python - 尝试制作随机字符串生成器

[英]Python - Trying to make a Random String Generator

I'm trying to make a String generator based on how much length you provided and it gets the alphabets from 2 arrays , One provided for Maj and one for Min , so that's my code but it usually returns "b" or error我正在尝试根据您提供的长度制作一个字符串生成器,它从 2 个数组中获取字母,一个为 Maj 提供,一个为 Min 提供,所以这是我的代码,但它通常返回“b”或错误

from random import randint
def randomstr(stringsize):
    Alphabet = ["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"]
    Alphabet2 = ["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"]
    i = stringsize+1
    LocalRanDom = ""
    StringGen = []
    while i < stringsize+1:
        i = i-1
    MajorMin = randint(1,2)
    print(Alphabet[1])
    if MajorMin == 1:
        LocalRanDom = randint(1,26)
        StringGen.append(Alphabet[LocalRanDom])
    if MajorMin == 2:
        LocalRanDom = randint(1,26)
        StringGen.append(Alphabet2[LocalRanDom])
    return StringGen 

randomstr(3)

This is not pythonic lol see Chris's comment这不是 pythonic 大声笑见克里斯的评论

First of all , I have no clue what the i is for?首先,我不知道 i 是什么? you just have it to i = stringsize+1 and then你只需要i = stringsize+1然后

while i < stringsize+1:
    i = i-1

after that, you never use it.在那之后,你永远不会使用它。

If you want a random String generator, you can do the following.如果您想要一个随机字符串生成器,您可以执行以下操作。

from random import random


def gen(length):
    string = ''
    for _ in range(length):
        shift = int(random()*26) # if you want cap letters, feel free to customzie
        asci = shift + 97
        string += chr(asci)
    return string

print(gen(3))

Your code is mostly unsalvageable but I'll go through it and explain all the issues I've encountered with it.您的代码大多无法修复,但我会仔细阅读并解释我遇到的所有问题。 You also didn't indent your code properly in your question so I've made some assumptions on that front.你也没有在你的问题中正确缩进你的代码,所以我在这方面做了一些假设。

Addressing Code Issues解决代码问题

Alphabet generation字母表生成

Alphabet = ["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"]`
Alphabet2 = ["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"]`

These could be more succinctly expressed as:这些可以更简洁地表示为:

lowercase_letters = list(string.ascii_lowercase)
uppercase_letters = list(string.ascii_uppercase)

Iteration logic迭代逻辑

Your current implementation will not iterate at all because you assign i = stringsize+1 and then create a while loop with the condition i < stringsize+1 - this will never be true when the condition is first evaluated .您当前的实现根本不会迭代,因为您分配i = stringsize+1然后创建一个 while 循环,条件i < stringsize+1 -这在第一次评估条件时永远不会为真

The correct and Pythonic approach would be to use a for loop like this:正确的 Pythonic 方法是使用这样的 for 循环:

for i in range(stringsize):
    ...

String concatenation字符串连接

Strings in Python are technically lists but it's not really very pleasant to construct strings by appending individual characters to a list. Python 中的字符串在技术上是列表,但通过将单个字符附加到列表来构造字符串并不是很愉快。

One approach would be to set StringGen = '' and then add characters to it using StringGen += c within the for loop.一种方法是设置StringGen = ''然后在 for 循环中使用StringGen += c添加字符。 However, this isn't efficient .但是,这效率不高 I'll provide a solution at the bottom of this post to demonstrate an implementation that does not involve concatenation within loops.我将在这篇文章的底部提供一个解决方案来演示一个不涉及循环内串联的实现。

Misusing integers for conditional logic在条件逻辑中滥用整数

The code:编码:

MajorMin = randint(1,2)
if MajorMin == 1:
    ...
if MajorMin == 2:
    ...

Could be made far clearer using this equivalent logic:使用这个等效逻辑可以更清楚:

use_uppercase_letter = random.choice([True, False])
if use_uppercase_letter:
    ...
else:
    ...

Alternative Implementations替代实现

Refined variation of your approach改进方法的变体

Here's a different implementation of randomstr that builds on the points here:这是基于此处的点的randomstr的不同实现:

import string
import random


def randomstr(stringsize):
    lowercase_letters = list(string.ascii_lowercase)
    uppercase_letters = list(string.ascii_uppercase)

    def generate_letters(n):
        for i in range(n):
            use_uppercase_letter = random.choice([True, False])
            if use_uppercase_letter:
                yield random.choice(lowercase_letters)
            else:
                yield random.choice(uppercase_letters)

    return ''.join(c for c in generate_letters(stringsize))


print(randomstr(10))

My best crack at it我最好的破解方法

This is a much more concise implementation that I'll offer in case you want it, but it deviates a lot from your original approach.这是一个更简洁的实现,如果您需要,我会提供它,但它与您原来的方法有很大的不同。

import string
import random


def randomstr(stringsize):
    letters = list(string.ascii_lowercase + string.ascii_uppercase)
    return ''.join(random.choice(letters) for _ in range(stringsize))


print(randomstr(10))

Example runs示例运行

These are the examples of the outputs you get with either of the implementations above.这些是您通过上述任一实现获得的输出示例。

MYXPupqiRG
ELNMPktrbe
ZnYBjlIxNQ

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM