首页 > 解决方案 > random.choices 和 if/else 语句

问题描述

我正在尝试列出一份清单,以便您了解姓名、他们的行为和行动。我只是似乎没有让我的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)))

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

标签: pythonpython-3.xpython-3.8

解决方案


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

将其更改为:

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

推荐阅读