简体   繁体   English

random.choices 和 if/else 语句

[英]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.我只是似乎没有让我的if/else语句起作用。 It only picks my else .它只选择我的else Never my if even though that should have a higher probability.从来没有我的if即使那应该有更高的概率。 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' ).那是因为random.choices返回一个list ,因此它永远不会等于一个字符串(例如'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返回 ak 大小的元素列表

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.它将返回一个list ,但是您将它与单个字符串'good'进行比较-它们永远不会相同,并且它总是会选择else块。

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. Random.choices 产生一个包含一个成员的列表。 To do a comparison against the string "good" you need to index to that item with n[0]要与字符串“good”进行比较,您需要使用 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在 if 语句给出这个 output 之前

['good'] good False False

which is fairly instructive as to what the problem is.这对于问题所在具有相当的指导意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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