Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

python - Creating an Array with an equal number of 0 and 1 in a random order?

Before I explain, here is my code for reference:

import numpy as np 

arrayteam = [[3,3,3,3,3,3],[2,2,2,2,2,2],[1,1,1,1,1,1]]
#nteams = 3
#nsubteam = 2

#newnums = np.zeros((len(arrayteam),len(arrayteam[0])))

subteam = [] 
for i in range(len(arrayteam)):
    subteam.append(np.random.choice([0,1],size=len(arrayteam[i]),p=[0.5,0.5]))

print (subteam)

Here is the output:

[array([0, 1, 0, 1, 1, 1]), array([1, 1, 0, 1, 0, 0]), array([1, 0, 1, 1, 1, 1])]

As you can see, it randomly chooses 0s and 1s which is what I want, however the number of 0s and 1s is unequal in each array, obviously because I have it as p=0.5, so there's a 50% chance it will choose 0 or 1. I want to have it so that there are 3 zeros and 3 ones in each array, but they occur in a random order. How can I do this?

Also, how can I end up changing exactly where I want the zeros and ones to occur? For example, what if I want the first 3 numbers in the array to be 0s, and the second 3 to be ones? Or what if I want them to alternate?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use random.shuffle. Note that it shuffles in-place, and returns None:

import random
length = 3
subteam = [0] * length + [1] * length
random.shuffle(subteam)
print(subteam)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...