计算 numpy 数组(列表)中元素的出现次数

我正在编写这个非常简单的代码来学习Python。我的目标是,获得当我多次掷两个骰子时可能出现的二项分布图。为此,我到目前为止编写了这些代码行:


    import random

    import numpy

    

    class Dice:

        def roll(self):

            first = random.randint(1, 6)

            return first



    class Dice2:   

        def roll(self):

            second = random.randint(1, 6)

            return second

   

   

    storage1 = []

    storage2 = []

    for rolling in range(10, 0, -1):

        dice = Dice()

        storage1.append(dice.roll())

        storage2.append(dice.roll())

    

    list1 = numpy.array((storage1)) + numpy.array((storage2))

    

    print(list1)

    

    

    x = 5

    count = 0

    

    for dice in list1:

        if(dice == x):

            count = count + 1

        print(count1)


所以我在这里想做的是输出一个元素的计数,在本例中 x = 5,换句话说,当我掷 2 个骰子时,我会抛出 5 多少次。尤其是最后一部分:


 list1 = numpy.array((storage1)) + numpy.array((storage2))

    

    print(list1)

    

    

    x = 5

    count = 0

    

    for dice in list1:

        if(dice == x):

            count = count + 1

        print(count1)


似乎不起作用,输出是我不明白的东西,它输出如下:


[ 2  7  7  8  7  4  7  9 10 10] 

  

#This is the output from the line: list1 = numpy.array((storage1)) + numpy.array((storage2))

# so this part I understand, it is the addition of dice1 and dice2, like wished


1

1

1

1

1

1

1

1

1

1


# This is the Output from the loop and finally the print(count1)

我想知道,如何存储出现次数,从 2 到 12 的任何数字(来自掷两个骰子)确实会出现。


慕哥9229398
浏览 117回答 1
1回答

慕斯709654

对代码进行简单修改即可获取滚动值的计数。如果您特别想使用 Numpy,请告诉我。代码from random import randint&nbsp; # only using randint so only import itimport numpy as np&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # not neededclass Dice:&nbsp; &nbsp; def roll(self):&nbsp; &nbsp; &nbsp; &nbsp; return randint(1, 6)frequencies = [0]*13&nbsp; &nbsp; &nbsp; &nbsp; # array to hold results of dice roll&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # will use frequencies 2 to 12)dice = Dice()remaining_rolls = 10000&nbsp; &nbsp; &nbsp;# number of remaining rolls&nbsp;while remaining_rolls > 0:&nbsp; &nbsp; roll = dice.roll() + dice.roll() # roll sum&nbsp; &nbsp; frequencies[roll] += 1&nbsp; &nbsp;# increment array at index roll by 1&nbsp; &nbsp; remaining_rolls -= 1&nbsp; &nbsp;&nbsp;print(frequencies)输出[0, 0, 272, 583, 829, 1106, 1401, 1617, 1391, 1123, 863, 553, 262]使用列表理解作为 while 循环的替代方案frequencies = [0]*13&nbsp;for roll in [dice.roll() + dice.roll() for _ in range(10000)]:&nbsp; &nbsp; frequencies[roll] += 1print(frequencies) # Simpler Output解释任务:frequencies = [0]*13创建一个包含 13 个元素的数组,索引从 0 到 12,最初用零填充。每个骰子的总和是 2 到 12 之间的数字(即 11 个值)为了增加一卷的计数,我们使用:&nbsp;frequencies[roll] += 1这是语法糖:frequencies[roll] = frequencies[roll] + 1例如,如果 roll = 5,我们将频率[5] 加 1,这会增加 roll 为 5 的次数的计数。两个 bin 始终为零:frequencies[0] and frequencies[1]这是因为 2 <= roll <= 12 所以我们永远不会增加 bin 0 和 1。
打开App,查看更多内容
随时随地看视频慕课网APP