【问题标题】:How do I attach a condition to a random choice?如何将条件附加到随机选择?
【发布时间】:2025-12-29 11:10:06
【问题描述】:

如果孩子在顽皮的名单上,我希望选择 5,但选择 6 会出现在好名单上。我的问题是分配给列表是元组值的随机选择。

import random, time # allowing use of random and delays
choice=[
'eddie',
'dan',
'erin',
'josh',
]

choices2=[
'naughty list',
'nice list'
]

choices3=[
'merry xmas anyhoooo!',
'cannot win them all!',
'have fun dude!',
'man\'s not got?',
]

choices4=[
'must have been when you pushed the granny over',
'could have been that cookie you stole?!',
'probably because you were cheeky to a teacher'
]

choices5=[
'must be because you are an angel',
'must be because you keep your room tidy',
'Santa just never saw you'
]
while True:
    input('\npress enter to check who is on the list')
    print('checking...')
    time.sleep(2)
    print(random.choice(choice))
    time.sleep(2)

    print(random.choice(choices2))
    if random.choice =='naughty list':
        print(random.choice(choices4))
    elif choices2=='nice list':
        print(random.choice(choices5))
    else:
        print('wrong')
    time.sleep(2)
    print(random.choice(choices3))

【问题讨论】:

    标签: python-3.x if-statement random


    【解决方案1】:

    更新代码:

     import random, time # allowing use of random and delays
    choice1=[
    'eddie',
    'dan',
    'erin',
    'josh',
    ]
    
    choices2=[
    'naughty list',
    'nice list'
    ]
    
    choices3=[
    'merry xmas anyhoooo!',
    'cannot win them all!',
    'have fun dude!',
    'man\'s not got?',
    ]
    
    choices4=[
    'must have been when you pushed the granny over',
    'could have been that cookie you stole?!',
    'probably because you were cheeky to a teacher'
    ]
    
    choices5=[
    'must be because you are an angel',
    'must be because you keep your room tidy',
    'Santa just never saw you'
    ]
    while True:
        input('\npress enter to check who is on the list')
        print('checking...')
        time.sleep(2)
        print(random.choice(choice1))
        time.sleep(2)
    
        list1 = random.choice(choices2)
        print(list1)
        if list1 =='naughty list':
            print(random.choice(choices4))
        elif list1=='nice list':
            print(random.choice(choices5))
        else:
            print('wrong')
        time.sleep(2)
        print(random.choice(choices3))
    

    另外,选择是随机函数内部使用的,因此将列表名称更改为选择1

    【讨论】:

    • 我不知道该怎么做 :-(