python - 如何使用random.choice 和alternation 循环?
问题描述
我正在尝试创建一个随机名称生成器,其中名称的长度为 8 个字符。我希望它在 1-2 个元音和 1-2 个辅音之间交替,直到达到 8 个字符长度。
找到答案,弄乱了这里代码的更新,所以我不得不删除它,但复选标记是正确的方法。
解决方案
您应该使用while
循环代替if
语句。
import random
vowels=('a', 'e', 'i', 'o', 'u', 'y')
consonants=('b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p',
'q', 'r', 's', 't', 'v', 'w', 'x', 'z')
full_name = random.choice(vowels) + random.choice(consonants)
while len(full_name) < 8:
full_name += random.choice(vowels) + random.choice(consonants)
else:
print(full_name)
推荐阅读
- php - 如何找到用户创建的按钮的值
- html - 在断点上使用 Bootstrap 4 的 Grid 自动调整列大小时,一旦浏览器变小,它们就会被永久忽略
- cryptography - 什么是 pkcs#11 密钥
- tcp - 在 tsung 负载测试期间,tcp 连接在 1024 个连接后关闭
- javascript - 如何修复 IE 11 中的日期解析
- spring-security - SpringSecurity 启用没有登录页面的 formLogin
- cobol - 错误:语法错误,意外的“文件”,期待“文件结束”
- javascript - 当 JSON 对象传递给变量时,转义字符丢失
- spring - 如何在一页中获取所有数据
- django - 如何通过单击按钮在后台提交 Django 表单?