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 returns a list,因此它永远不会等于 字符串(例如'good')。

改为:

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

来自the documentation

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

Return a k sized list of elements

它会 return 一个 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 语句给出此输出之前

['good'] good False False

这对问题是什么很有指导意义。