如何改善随机字串产生器

如何解决如何改善随机字串产生器

我设法创建了一个简单的随机字符串生成器,该生成器可以打印x倍的随机字母字符串,列表中的每个迭代的随机长度在3到10个字符之间。我是Python的新手,并且仍在学习基础知识,所以请多多包涵。我的程序按预期工作,但是我很确定我的代码可以优化。我真的很想学习最佳实践并扩展我的知识。这是我的第一篇文章。抱歉,如果我在错误的位置。

import random

class Randomize:
    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']
    choice1 = random.choice(alphabet)
    choice2 = random.choice(alphabet)
    choice3 = random.choice(alphabet)
    choice4 = random.choice(alphabet)
    choice5 = random.choice(alphabet)
    choice6 = random.choice(alphabet)
    choice7 = random.choice(alphabet)
    choice8 = random.choice(alphabet)
    choice9 = random.choice(alphabet)
    choice10 = random.choice(alphabet)
    three_letters = choice1 + choice2 + choice3
    four_letters = choice1 + choice2 + choice3 + choice4
    five_letters = choice1 + choice2 + choice3 + choice4 + choice5
    six_letters = choice1 + choice2 + choice3 + choice4 + choice5 + choice6
    seven_letters = choice1 + choice2 + choice3 + choice4 + choice5 + choice6 + choice7
    eight_letters = choice1 + choice2 + choice3 + choice4 + choice5 + choice6 + choice7 + choice8
    nine_letters = choice1 + choice2 + choice3 + choice4 + choice5 + choice6 + choice7 + choice8 + choice9
    ten_letters = choice1 + choice2 + choice3 + choice4 + choice5 + choice6 + choice7 + choice8 + choice9 + choice10
    word_length = [three_letters,four_letters,five_letters,six_letters,seven_letters,eight_letters,nine_letters,ten_letters]
    word = random.choice(word_length)

def gen(self):
    for i in range(10):
        print (Randomize.word)
        Randomize.choice1 = random.choice(Randomize.alphabet)
        Randomize.choice2 = random.choice(Randomize.alphabet)
        Randomize.choice3 = random.choice(Randomize.alphabet)
        Randomize.choice4 = random.choice(Randomize.alphabet)
        Randomize.choice5 = random.choice(Randomize.alphabet)
        Randomize.choice6 = random.choice(Randomize.alphabet)
        Randomize.choice7 = random.choice(Randomize.alphabet)
        Randomize.choice8 = random.choice(Randomize.alphabet)
        Randomize.choice9 = random.choice(Randomize.alphabet)
        Randomize.choice10 = random.choice(Randomize.alphabet)
        Randomize.three_letters = Randomize.choice1 + Randomize.choice2 + Randomize.choice3
        Randomize.four_letters = Randomize.choice1 + Randomize.choice2 + Randomize.choice3 + Randomize.choice4
        Randomize.five_letters = Randomize.choice1 + Randomize.choice2 + Randomize.choice3 + Randomize.choice4 + Randomize.choice5
        Randomize.six_letters = Randomize.choice1 + Randomize.choice2 + Randomize.choice3 + Randomize.choice4 + Randomize.choice5 + Randomize.choice6
        Randomize.seven_letters = Randomize.choice1 + Randomize.choice2 + Randomize.choice3 + Randomize.choice4 + Randomize.choice5 + Randomize.choice6 + Randomize.choice7
        Randomize.eight_letters = Randomize.choice1 + Randomize.choice2 + Randomize.choice3 + Randomize.choice4 + Randomize.choice5 + Randomize.choice6 + Randomize.choice7 + Randomize.choice8
        Randomize.nine_letters = Randomize.choice1 + Randomize.choice2 + Randomize.choice3 + Randomize.choice4 + Randomize.choice5 + Randomize.choice6 + Randomize.choice7 + Randomize.choice8 + Randomize.choice9
        Randomize.ten_letters = Randomize.choice1 + Randomize.choice2 + Randomize.choice3 + Randomize.choice4 + Randomize.choice5 + Randomize.choice6 + Randomize.choice7 + Randomize.choice8 + Randomize.choice9 + Randomize.choice10
        Randomize.word_length = [Randomize.three_letters,Randomize.four_letters,Randomize.five_letters,Randomize.six_letters,Randomize.seven_letters,Randomize.eight_letters,Randomize.nine_letters,Randomize.ten_letters]
        Randomize.word = random.choice(Randomize.word_length)

name = Randomize()
name.gen()
print('Generated 10 names.')

编辑*

我发现我收到的建议的组合效果最好。这是比我的第一次尝试大得多的新版本。使用.join和参数k设置每个字符串生成的长度对我来说是一个巨大的启示。谢谢。

import random

def gen():
    ltrs = list('abcdefghijklmnopqrstuvwxyz')
    word = "".join(random.choices(ltrs,k=random.randint(3,10)))
    for i in range(1000):
        print(word)
        word = "".join(random.choices(ltrs,10)))

gen()

解决方法

欢迎来到该网站!

有几种方法可以从集合中随机选择事物。您可以在以下位置查看Dox:

random.choice()
random.choices()
random.sample()

寻求灵感。另外,numpy库具有一些选项。

如果要替换样品 ,那么random.choices是一个不错的选择

In [7]: from random import choices   

In [11]: a = list('abcdefghijklmnopqrstuvwxyz')                                                             

In [12]: choices(a,k=10)                                                                                   
Out[12]: ['l','a','c','y','s','u','n','g','n']

In [13]:  
,

这里有些地方可能需要改进。

首先,在此示例中,“随机化”不必是一个类,而只能由单个函数代替(我们将其称为randomWord())。 其次,您可以使用已经使用的相同random库(只是具有不同的功能(random.randint)来选择要使用的字母数。 最后,有一种获取小写字母(string.ascii_lowercase)的内置方法,因此无需自己输入。

这是您可以使用的一些示例代码:

import random
from string import ascii_lowercase as alphabet

def randomWord():
    length = random.randint(3,10) # randint gives you a random number between the two arguments,inclusive
    word = "" # initialises an empty string that we will build up with letters
    for i in range(length): # iterates 'length' times
        word += random.choice(alphabet) # this appends a new random letter to the word we're building up
    return word

print(randomWord())
print("We printed a random word between 3 and 10 characters!")

您当然可以将randomWord()放入for循环中,以获得10个随机词。

,

这个

alphabet = ['a','b','d','e','f','h','i','j','k','l','m','o','p','q','r','t','v','w','x','z']

等效于此

import string
alphabet = string.ascii_lowercase

然后,您可以使用一种方法来生成具有长度的随机字符串

def get_random_string(length):
    alphabet = string.ascii_lowercase
    result_str = ""
    for i in length:
        result_str += random.choice(alphabet) 
    return result_str

最终使用它来不确定地生成随机字符串

for i in range(10):
    length = random.randint(3,9)
    random_string = get_random_string(length)
    print(random_string)

生成的脚本将是

import string
import random
alphabet = string.ascii_lowercase

def get_random_string(length):
    alphabet = string.ascii_lowercase
    result_str = ""
    for i in length:
        result_str += random.choice(alphabet) 
    return result_str

for i in range(10):
    length = random.randint(3,9)
    random_string = get_random_string(length)
    print(random_string)
,

Python有一些有趣的语法快捷方式,一旦学会,它们可以在几行代码中完成很多工作。手动分配可以通过循环自动执行,并且可以压缩循环 理解力,这是Python的最佳功能之一。

首先,您可以生成字母字符串,而无需导入单独的字符串 像字符串一样的模块,使用ascii排序。这里''.join()从列表中制造出一个字符串,这不是严格必要的,并且该列表是使用chr()ord()方法构造的(请注意不存在的错误)>

ltrs = ''.join([chr(x) for x in range(ord('a'),ord('z') + 1)])   
>>> 'abcdefghijklmnopqrstuvwxyz'

您可以仅从库中导入所需的一个函数randint,然后使用另一种列表理解来生成单词:

from random import randint
def gen_word(minlen,maxlen,ltrs):
    wordlen = randint(minlen,maxlen + 1)
    return ''.join([ltrs[randint(len(ltrs)] for _ in range(wordlen)])

要使用另一种列表理解来生成10个单词,请执行以下操作:

mywordlist = [gen_word(3,10,ltrs) for _ in range(10)]

使用此功能,ltrs可以是任何字符串或字符序列。 “ _”是标准语法,指示变量是一次性的,在这种情况下仅用于运行循环。要学习的真正关键是如何进行循环并将其转换为列表推导。您可以尝试使用上面M. Iduoad提供的代码来练习这一点。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-