简体   繁体   English

在Python数组中生成整数随机数

[英]Generate Integer Random Numbers in Python Array

I'm trying to make an array with 30 integer elements between 0 and 2 randomly chosen. 我正在尝试制作一个数组,其中包含30个随机选择的介于0和2之间的整数元素。 When some number is chosen 10 times, i can't append it anymore. 当某个数字被选择10次时,我再也不能追加它了。 In the end, I need an array with 30 elements with 10 numbers 0, 10 numbers 1 and 10 numbers 2. Here's what i'm trying: 最后,我需要一个包含30个元素的数组,其中包含10个数字0、10个数字1和10个数字2。这是我正在尝试的方法:

import random
array_size = 30
number = 3
counter = [0, 0, 0]
solution = []

for i in range(array_size):
    number = random.randrange(number) #generates numbers between 0 and 2

    while counter[number] > 10:
        number = random.randrange(number)

    counter[number] += 1
    solution.append(number)

As result, i have more than 10 elements of the same number. 结果,我有10个以上相同编号的元素。 I believe the problem is in the random number that i put in the while is not changed even if i change it inside the loop. 我相信问题出在即使我在循环中更改随机数也不会改变。 Someone know how to do this? 有人知道该怎么做吗?

Thanks 谢谢

Just change 只是改变

while number[counter] > 10:

to

while number[counter] >= 10:

Originally your code would only stop appending a certain number only if there were more than 10 instances of it within your array. 最初,只有在数组中有10个以上实例的情况下,您的代码才会停止追加特定数量。 By changing it to a >=, the program will stop appending the number the moment it adds it for a tenth time. 通过将其更改为> =,程序将在第十次添加数字时停止添加数字。

import math
import random

number = 3
size = 30

steps = math.ceil(size / number)

solution = []
for x in range(steps):
    for n in range(number):
        solution.append(n)

random.shuffle(solution)
print(solution)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM