获取范围内随机数选择中整数出现次数 N 次

Get count of occurrence of integers in a random number selection in a range N times

在编写这段代码时,我发现自己做了很多重复的事情,想知道是否有更简单、更简单或更短的方法来完成这样的重复性任务。

相关代码如下:

 from random import randint
    RandomNumber = Zeroes = Ones = Twos = Threes = Fours = Fives = Sixes = i = 0

    while i < 1000000:
        RandomNumber = (randint(0,6))
        if RandomNumber == 0:
            Zeroes = Zeroes + 1
        if RandomNumber == 1:
            Ones = Ones + 1
        if RandomNumber == 2:
            Twos = Twos + 1
        if RandomNumber == 3:
            Threes = Threes + 1
        if RandomNumber == 4:
            Fours = Fours + 1
        if RandomNumber == 5:
            Fives = Fives + 1
        if RandomNumber == 6:
            Sixes = Sixes + 1

        i = i + 1

首先,当您发现自己使用大量适合相同目的的变量(例如零、一、二等的数量)时,您几乎肯定需要一个数组([=26 中的 list =] 术语)。

import random

nums = [0] * 7 # number of digits from zero to six

for i in range(1000001):
    r = random.randint(0, 6) # you can get rid of this variable 
                             # and use random.randint(0, 6) as an array index
    nums[r] += 1 # each member of a list represents a number of some digit's occurrences

print(''.join("{} -> {}\n".format(a, b) for a, b in zip(range(7), nums)))

如果你想要非常 短、快、强大的东西:

import random, collections

print(''.join("{} -> {}\n".format(a, b) for a, b in collections.Counter(random.randint(0, 6) for _ in range(100)).items()))

检查 this 以了解如何计算具有 collections.Counter 的列表项的出现次数。

此代码速度很快,并且不会因为使用生成器而浪费内存。

给你...

from random import randint
outcomes=[0]*7
for i in range(1000000):
    outcomes[randint(0,6)]+=1

在你的特殊情况下你可以这样做

from random import randint
results=[0]*7 # same as [0,0,0,0,0,0,0]

i=0
while i < 1000000:
    n = randint(0,6)
    results[n]+=1
    i+=1

for i in range(len(results)):
    print(i, results[i])

此代码可能会有所帮助,计数器字典会将数字保存为键,将出现的数字作为值。

from random import randint

counter = {}

while i < 1000000:
    RandomNumber = (randint(0,6))
    if RandomNumber in counter:
        counter[RandomNumber] += 1
    else:
        counter[RandomNumber] = 1

    i += 1

您可以将包含每个可能值的字典作为键,而不是为每个随机输出取命名变量。这将缩短您的代码并使其可扩展到任何随机范围

from random import randint
randomMax = 6
randomList= {i:0 for i in range(0,randomMax+1)}
totalIterations = 10000
while totalIterations >0:
    randomList[randint(0,randomMax)]+=1
    totalIterations-=1

示例输出:

{0: 1400, 1: 1400, 2: 1500, 3: 1400, 4: 1500, 5: 1000, 6: 1800}

这些答案都有效,但它们将花费 非常 很长时间来循环,而实际上您根本不需要使用循环。这是需要固定时间而不需要循环超过一百万次的代码:

from random import random

nums = [random() for _ in range(7)]
nums = [int((x / sum(nums)) * 1000000) for x in nums]

不可否认,此方法总共会减少 1000000,但快很多,您还可以在随机数中添加一点,使其实际为 1000000 .

有关详细信息,请参阅:

Getting N random numbers that the sum is M

Random numbers that add to 100: Matlab(有关由此生成的统计分布的信息)