繁体   English   中英

random.choices 和 if/else 语句

[英]random.choices and if/else statements

我正在尝试列出一份清单,以便您了解姓名、他们的行为和行动。 我只是似乎没有让我的if/else语句起作用。 它只选择我的else 从来没有我的if即使那应该有更高的概率。 这是我的代码:

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

今年我所有的东西都只是名字不好,所以他们得到了,然后是煤炭或角落......

那是因为random.choices返回一个list ,因此它永远不会等于一个字符串(例如'good' )。

将其更改为:

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

文档中

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

返回 ak 大小的元素列表

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

例如,您可以:

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

或者:

    if n[0] == 'good':

Random.choices 产生一个包含一个成员的列表。 要与字符串“good”进行比较,您需要使用 n[0] 对该项目进行索引

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

我发现抛出一个打印语句来比较变量并验证它们是我认为的那样很有帮助。 这是测试问题的好方法。 像这样的测试打印

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

在 if 语句给出这个 output 之前

['good'] good False False

这对于问题所在具有相当的指导意义。

暂无
暂无

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

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