Randomly select 0 or 1 equal number of times?

ken*_*nny 4 python random

I want to iterate over 100 values and select randomly 0 or 1, but end up with equal numbers of 0's and 1's,

The code below prints the counts:

import random
c_true = 0
c_false = 0

for i in range(100):
    a = random.getrandbits(1)
    if a == 1:
        c_true += 1
    else:
        c_false += 1

print "true_count:",c_true
print "false_count:",c_false
Run Code Online (Sandbox Code Playgroud)

The output is:

true_count: 56
false_count: 44
Run Code Online (Sandbox Code Playgroud)

我希望计数是平等的

true_count: 50
false_count: 50
Run Code Online (Sandbox Code Playgroud)

如何更改代码以获得所需的结果?

the*_*eye 8

  1. 创建numbers50 0和50 1,

    >>> numbers = [0, 1] * 50
    
    Run Code Online (Sandbox Code Playgroud)
  2. 从中导入shufflerandom

    >>> from random import shuffle
    
    Run Code Online (Sandbox Code Playgroud)
  3. shuffle 他们

    >>> shuffle(numbers)
    
    Run Code Online (Sandbox Code Playgroud)

注意: shuffle就地清单列表.所以,numbers现在将改组.