python - 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)))
今年我所有的东西都只是名字不好,所以他们得到了,然后是煤炭或角落......
解决方案
那是因为random.choices
返回一个list,因此它永远不会等于一个字符串(例如'good'
)。
将其更改为:
n = random.choices(behaviour, weights=(3,1))[0]
推荐阅读
- python - 如何用pynput按windows键?
- html - VF:是否可以只显示数据表中的特定行?
- mongodb - Golang中创建mongodb索引的方法
- python - Conda 使用 .yml 文件创建环境失败
- python - on_message 问题时未向用户发送消息
- python - 有没有办法阻止 rpy2 自动转换所有内容?
- python - Seaborn 热图混淆矩阵显示未按预期显示
- javascript - 在 ChartJS 中将两个折线图合二为一
- r - 如何同时删除破折号 (-) 和 \n 或对此文本清理的一些解决方案
- java - 由于 Java 即时编译,我是否应该期望 Mockito 测试中的方法中没有的代码运行得更快?