擅长:python、mysql、java
<pre class="lang-py prettyprint-override"><code>from random import randint, choice
ball_choices = ['rolled', 'bounced']
cat_choices = ['purred', 'meowed']
if randint(0, 1):
print ('The ball ', choice(ball_choices))
else:
print ('The cat', choice(cat_choices))
</code></pre>
<p>这将随机生成0或1,如果为1,则打印随机选择的球串,如果为0,则打印随机选择的猫串。这有意义吗</p>
<p><em>Edit:如果您想添加更多选项,您可以随时更改<code>randint()</code>的范围,并为每个范围设置条件,但这可以非常容易地通用化(为您节省大量键入时间),如下所示:</em></p>
<pre class="lang-py prettyprint-override"><code>options = {
'ball': ['rolled', 'bounced'],
'cat': ['purred', 'meowed'],
'tv': ['turned on', 'turned off', 'exploded'],
# Add more here...
}
# Pick a random item from the keys of options
random_item = choice(list(options))
# Print the item and choose randomly from that option's choices
print('The', random_item, choice(options[random_item]))
</code></pre>
<p>现在,只需向<code>options</code>添加更多条目,就可以添加更多的选择和选项</p>