简体   繁体   中英

random.choices and if/else statements

I am trying to make a list so that you will have a name, their behavior and an action. I just don't seem to get my if/else statement to work. It only picks my else . Never my if even though that should have a higher probability. This is my code:

import random

Names = ['john', 'james', 'dave', 'ryan']
behaviour = ['good', 'bad']
good = ['candy', 'presents', 'hug']
bad = ['get coal', ' have to stand in the corner']
for i in Names:
    n = random.choices(behaviour,weights=(3,1))
    k = random.choice(bad)
    if n=='good':
         print('{} was good this year therefor they get {}'.format(i,random.choice(good)))
    else:
         print('{} was bad this year therefor they {}'.format(i,random.choice(bad)))

all my things are just name was bad this year therefore they get and then either coal or the corner.....

That's because random.choices returns a list , therefore it'll never be equal to a string (eg 'good' ).

Change it to:

n = random.choices(behaviour, weights=(3,1))[0]

From the documentation :

random.choices(population, weights=None, *, cum_weights=None, k=1)

Return ak sized list of elements

It will return a list , but you're comparing it to a single string 'good' - they will never be the same and there it always picks the else block.

You could, for example:

    if n == ['good']:
         print('{} was good this year therefor they get {}'.format(i,random.choice(good)))
    else:
         print('{} was bad this year therefor they {}'.format(i,random.choice(bad)))

Or:

    if n[0] == 'good':

Random.choices yields a list with one member. To do a comparison against the string "good" you need to index to that item with n[0]

if n[0]=='good':
         print('{} was good this year therefor they get {}'.format(i,random.choice(good)))

I find it's helpful to throw a print statement to compare variables and verify they are what i think they are. It's a good way to test for problems. A test print like this

print(n, 'good', n=='good', str(n)=='good')

before the if statements gives this output

['good'] good False False

which is fairly instructive as to what the problem is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM