이미 매트릭스가 있다고 가정 할 때 한 가지 방법이 있습니다. 이 출력 제공
import pprint
import random
categories = [0,1,3] #complete pool of numbers
restrictedNumbers = [0, 1] #numbers to only appear once
unrestrictedNumbers = [num for num in categories if num not in restrictedNumbers] #can appear any number of times
matrix = [[0, 0, 0, 0, 0] for l in range(10)] #10 rows, 5 columns matrix of zeros
newMatrix = []
for row in matrix:
tempRow = restrictedNumbers #first add the restricted numbers since they must appear once
while len(tempRow) < len(row): #keep adding numbers from unrestricted till lengths are equal
tempRow.append(random.choice(unrestrictedNumbers))
random.shuffle(tempRow)
newMatrix.append(tempRow[:]) #finally add the shuffled row to newMatrix
pprint.pprint(newMatrix)
(문제는, 매트릭스를 작성하지 행렬을 채우기 말한다) :
[[3, 1, 3, 0, 3],
[3, 3, 0, 1, 3],
[0, 3, 1, 3, 3],
[0, 3, 1, 3, 3],
[3, 3, 0, 3, 1],
[0, 1, 3, 3, 3],
[1, 0, 3, 3, 3],
[1, 3, 0, 3, 3],
[3, 3, 0, 3, 1],
[3, 0, 1, 3, 3]]
당신은 각 라인이있다 볼 수있다 (분명히 있기 때문에 임의의 다릅니다)를 하나의 0 하나의 1
다음
의 더 짧은 방법 :
import pprint
import random
categories = [0,1,3] #complete pool of numbers
restrictedNumbers = [0, 1] #numbers to only appear once
unrestrictedNumbers = [num for num in categories if num not in restrictedNumbers] #can appear any number of times
matrix = [[0, 0, 0, 0, 0] for l in range(10)] #10 rows, 5 columns matrix of zeros
newMatrix = []
for row in matrix:
row = restrictedNumbers + [random.choice(unrestrictedNumbers) for _ in range(len(row)-len(restrictedNumbers))]
random.shuffle(row)
newMatrix.append(row)
pprint.pprint(newMatrix)
그리고
import pprint
import random
categories = [0,1,3] #complete pool of numbers
restrictedNumbers = [0, 1] #numbers to only appear once
unrestrictedNumbers = [num for num in categories if num not in restrictedNumbers] #can appear any number of times
matrix = [[0, 0, 0, 0, 0] for l in range(10)] #10 rows, 5 columns matrix of zeros
def returnShuffled(startList):
random.shuffle(startList)
return startList
newMatrix = [returnShuffled(restrictedNumbers + [random.choice(unrestrictedNumbers) for _ in range(len(row) - len(restrictedNumbers))]) for row in matrix]
pprint.pprint(newMatrix)
당신이 뭐라고 10 × 5는 10 개 개의 요소 각각 목록을 의미합니까 (random.shuffle 대신 장소에서 셔플의 목록을 반환하는 경우이 한 줄 것) 것보다 훨씬 더 짧은 5 개의 요소를 포함하는 목록 또는 각각 10 개의 요소를 포함하는 5 개의 요소가있는 목록? – Keatinge
감사합니다 Keatinge, 내 A는 10 행 5 열을 가진 배열입니다. 감사합니다 – user1301295
제가 원했던 것은'np.random.choice ([0, 1, 3], 10 * 5, size = (10,5))'와 거의 비슷합니다. 한 번은 0 번 발생하고 한 번만 '1 번'번 발생합니다. – user1301295