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)
如何更改代码以获得所需的结果?
创建numbers
50 0和50 1,
>>> numbers = [0, 1] * 50
Run Code Online (Sandbox Code Playgroud)>>> from random import shuffle
Run Code Online (Sandbox Code Playgroud)shuffle
他们
>>> shuffle(numbers)
Run Code Online (Sandbox Code Playgroud)注意: shuffle
就地清单列表.所以,numbers
现在将改组.