【问题标题】:Sentence generator with words from lists using Python使用 Python 使用列表中的单词生成句子
【发布时间】:2019-09-08 16:38:21
【问题描述】:

所以我正在尝试学习 python,并且我已经编写了这段代码,它应该从随机单词和随机数列表中生成句子,我已经开始使用这段代码,但我不确定它是否会工作

这是我的代码:

import random

num = random.randrange(0, 9)
drug = ['Advil', 'Synthroid', 'Crestor', 'Nexium', 'Vyvanse', 'Lyrica']
form = ['capsule', 'tablet', 'Powder', 'gel', 'liquid solution', 'Eye drops']

lines = []
for item in drug, form:
    line = '- the patient was prescribed [' + num + '](dosage) [' + item.form + '](form) of [' + item.drug + '] for [' + num + 'days](Duration)
    lines.append(line)

这是我期待的结果:

[the patient was prescribed [1](Dosage) [capsule](Form) of [Advil](Drug) for [5 days](Duration),
the patient was prescribed [2](Dosage) [Powder](Form) of [Nexium](Drug) for [6 days](Duration),
the patient was prescribed [5](Dosage) [luiquid solution](Form) of [Vyvanse](Drug) for [4 days](Duration),
...]

【问题讨论】:

  • 你的代码里的药物是什么?
  • 我的意思是 ''for item in drug, form:''

标签: python python-3.x random


【解决方案1】:

你可以这样做

import random

## generate 6 random numbers
nums = [random.randrange(0, 9) for _ in range(6)] 
days = nums = [random.randrange(0, 9) for _ in range(6)]
drugs = ['Advil', 'Synthroid', 'Crestor', 'Nexium', 'Vyvanse', 'Lyrica']
forms = ['capsule', 'tablet', 'Powder', 'gel', 'liquid solution', 'Eye drops']

lines = []
## zip will take one element from each array at one time
for num, drug, form, day in zip(nums, drugs, forms, days):
    ## this is string formatting syntax in python you put your local 
    ## variable inside curly brackets
    line = F"- the patient was prescribed {num} dosage {form} of {drug} for {day} days"
    lines.append(line)

print(lines)

【讨论】:

    猜你喜欢
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    相关资源
    最近更新 更多