如何使用Python生成包含80%True与20%False的布尔值列?
Got it, let's sort this out for you! The issue with your current code using random.choice([True, False]) is that it gives an equal 50/50 chance for each value, so you can't lock in that exact 80/20 split. Here are two reliable approaches to get the precise ratio you need:
方法1:构造固定比例列表后打乱(保证精确比例)
This method ensures you get exactly 80% True and 20% False every time, with random ordering. First, build a list with the correct number of True/False values, then shuffle it to randomize the sequence:
import random # 替换成你需要的总元素数量 total_entries = 10 # 10个元素的话就是8个True,2个False,完美匹配80/20 # 如果是4个元素(像你原来的循环),可以用3个True和1个False(接近80%) # total_entries = 4 # 按比例生成True和False的列表 pass_column = [True] * int(total_entries * 0.8) + [False] * int(total_entries * 0.2) # 打乱顺序,让分布随机 random.shuffle(pass_column) print(pass_column)
注意事项
If total_entries * 0.8 isn't an integer (like 4*0.8=3.2), you'll need to decide whether to round up, round down, or adjust the total count to get a clean split. For example, use round(total_entries * 0.8) instead of int() if you want a closer approximate ratio for small datasets.
方法2:使用带权重的随机选择(概率趋近于80/20)
If you don't need absolute precision (just a long-term 80/20 ratio), you can use random.choices() which lets you assign weights to each option:
import random total_entries = 10 # weights=[0.8, 0.2] 表示True有80%概率被选中,False有20% pass_column = random.choices([True, False], weights=[0.8, 0.2], k=total_entries) print(pass_column)
This is simpler for large datasets where small deviations from the exact ratio don't matter, but for small sample sizes (like 4 elements), it might occasionally give a split that's not exactly 80/20.
为什么你的原代码没生效?
Your original loop just picks True/False randomly each time, so there's no guarantee of the 80/20 split. For example, in 4 iterations, you might end up with 2 True and 2 False, or 3 True and 1 False—there's no control over the final ratio.
内容的提问来源于stack exchange,提问作者Ankur Kumar

