如何在多个打印命令之间随机选择?

2024-03-29 11:17:30 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在多个打印命令之间随机选择

例如

我想随机选择这两个打印函数中的一个

print ('The ball ', (random.choice (action_ball))
print ('The cat', (random.choice (action_cat))

然后参考这两个列表

action_ball = ['rolled','bounced']
action_cat = ['purred','meowed']

要随机生成这四个句子中的一个

the ball rolled
the ball bounced
the cat purred
the cat meowed

我了解如何从一个列表生成:

import random
action_ball = ['rolled','bounced']
print ('The ball ', (random.choice (action_ball))

在那之后,我迷路了


2条回答
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))

这将随机生成0或1,如果为1,则打印随机选择的球串,如果为0,则打印随机选择的猫串。这有意义吗

Edit:如果您想添加更多选项,您可以随时更改randint()的范围,并为每个范围设置条件,但这可以非常容易地通用化(为您节省大量键入时间),如下所示:

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]))

现在,只需向options添加更多条目,就可以添加更多的选择和选项

您可以提前生成所有四个句子,然后只需选择其中一个:

from random import choice
src = [('The ball',('rolled','bounced')),('The cat',('purred','meowed'))]
all = [sentence[0] + ' ' + word for sentence in src for word in sentence[1]]

for _ in range(5):   # arbitrary number of repetitions
    print(choice(all))

相关问题 更多 >