在python中生成随机句子
我是 python 和编程的新手!
我需要编写一个程序,其中包含 4 个元组,每个元组包含 5 个元素。一个元组应该有动词,一个元组应该有名词,一个元组应该有形容词,一个元组应该有副词。然后我必须使用 0 到 4 之间随机生成的数字从每个元组中选择一个元素。这是我到目前为止所拥有的:
import randomnouns = ("puppy", "car", "rabbit", "girl", "monkey")
verbs = ("runs", "hits", "jumps", "drives", "barfs")
adv = ("crazily.", "dutifully.", "foolishly.", "merrily.", "occasionally.")
adj = ("adorable", "clueless", "dirty", "odd", "stupid")
num = random.randrange(0,5)
print (num)
有人可以告诉我我做错了什么吗?
原文由 Ashley Glover 发布,翻译遵循 CC BY-SA 4.0 许可协议
回答:
最简单的理解方式:
import randomnouns = ("puppy", "car", "rabbit", "girl", "monkey")
verbs = ("runs", "hits", "jumps", "drives", "barfs")
adv = ("crazily.", "dutifully.", "foolishly.", "merrily.", "occasionally.")
adj = ("adorable", "clueless", "dirty", "odd", "stupid")
num = random.randrange(0,5)
print nouns[num] + ' ' + verbs[num] + ' ' + adv[num] + ' ' + adj[num]
原文由 Avión 发布,翻译遵循 CC BY-SA 3.0 许可协议
回答:
您可以在列表理解中使用 random.choice
然后将所选列表与 join
连接:
>>> l=[nouns,verbs,adj,adv]>>> ' '.join([random.choice(i) for i in l])
'girl runs dirty crazily.'
>>> ' '.join([random.choice(i) for i in l])
'monkey hits clueless occasionally.'
原文由 Mazdak 发布,翻译遵循 CC BY-SA 3.0 许可协议
以上是 在python中生成随机句子 的全部内容, 来源链接: utcz.com/p/938668.html