在列中生成 True 和 False 的 Python 代码
我分配了一项任务来创建一个列,其中包含布尔值“真/假”,表示“通过”,但有一个特定条件,即该列应具有 80% 的真值和 20% 的假值。
我尝试使用随机 True/False 值创建 Pass 列,但无法了解如何生成 8/10 true 和其余 False。
我的代码如下:
Pass=[]
i=1
while i<5:
choices=random.choice([True,False])
Pass.append(choices)
i+=1
请帮我提供建议或代码块以供参考。谢谢
I have assigned a task to create a column saying "Pass" with boolean values - "true/false" but with a certain condition that the column should have 80% True values and 20% False.
I tried creating the column Pass with random True/False values but was unable to get how to generate 8/10 true and remaining False.
My code is below:
Pass=[]
i=1
while i<5:
choices=random.choice([True,False])
Pass.append(choices)
i+=1
Please help me with suggestions or a block of code for reference. Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
continue
You can use
random.choices
and provide weights:random.choices
can return multiple samples, so it gives you a one-element list. If if you already know how many values you need (number of rows), you can also tellchoices
how many it should generate:According to the documentation, you can save a little work by supplying cumulated weights instead of weights:
tl;dr:
您可以使用
random.choice 设置概率()
与p
参数。输出:
You can set the probablity with
random.choice()
with thep
-parameter.Output: