python - 有什么方法可以返回将作为长度为 8 的字符串输出的随机辅音或元音?
问题描述
我对计算机科学完全陌生,不确定如何收集结果并将它们作为 8 个字符串返回给用户。
这是我根据用户要求为用户提供 8 个随机辅音或元音的代码。
count = 2
while count < 10:
char = input("v or c")
if char == "v":
vow = ['a', 'e', 'i', 'o', 'u']
v = random.choice(vow)
print(v)
count = count + 1
if char == "c":
con = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's',
't', 'v', 'w', 'x',
'y', 'z']
c = random.choice(con)
print(c)
count = count + 1`
解决方案
只需在列表或字符串中收集随机选项:
vowels = 'aeiou' # random.choice can choose from any type of sequence
consonants = 'bcdfghjklmnpqrstvwxyz'
chars = [] # collects the choices
for _ in range(8): # for loop if iteration count is known beforehand
select_char = input("Please enter either v for a vowel or c for a consonant: ")
if select_char == "v":
chars.append(random.choice(vowels))
else:
chars.append(random.choice(consonants))
print(''.join(chars))
推荐阅读
- android - Android Gradle 添加原生库
- angular - 在 Angular 7 应用程序中使用 google-api-nodejs-client
- python - 仅从 Jupyter Notebook 中获取代码
- scala - 每列值的火花计数和百分比异常处理和加载到 Hive DB
- ubuntu - unison:如何同步多个目录中的特定子文件夹?
- r - dplyr 取消引用不适用于过滤器功能
- python - 如何使用 tkinter 将剪贴板中的图像数据保存到 Debian 上的 Python 3 中的文件?
- r - if (by == 0 && del == 0) return(from) 出错:需要 TRUE/FALSE 的缺失值
- webpack - Webpack Scaffold webpackOptions 合并不起作用,为什么?
- google-chrome - 捕获任何 JavaScript 重定向