【问题标题】:How can I randomly choose between multiple print commands?如何在多个打印命令之间随机选择?
【发布时间】:2021-02-10 05:05:20
【问题描述】:

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

比如……

我想随机选择这两个打印功能之一...

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

在那之后,我迷路了。

【问题讨论】:

    标签: python list random printing


    【解决方案1】:

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

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

    【讨论】:

    • 可能值得注意的是,随着选项数量的增加,这会产生大量开销。
    • 谢谢。
    【解决方案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,则打印随机选择的猫字符串。这有意义吗?

    编辑:如果您想添加更多选项,您可以随时更改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 添加更多条目即可添加其他选择和选项。

    【讨论】:

    • 谢谢。确实如此。而且,添加选择意味着增加“randint”范围并添加更多“else”语句?
    • 当然,您可以增加randint() 的范围,或者您可以做另一个“选择”并使用该选择(我认为这更直观一些)。我将在我的答案中添加一个示例。
    • 谢谢。这很有帮助。
    猜你喜欢
    • 1970-01-01
    • 2019-08-19
    • 2014-01-01
    • 1970-01-01
    • 2012-12-23
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    相关资源
    最近更新 更多