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

Count occurrence´s of Element in numpy array (list)

我正在编写这个非常简单的代码来了解 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(从掷两个骰子)中的任何数字确实会出现。

对您的代码进行简单修改以获取滚动值的计数。如果您特别想使用 Numpy,请告诉我。

代码

from random import randint  # only using randint so only import it
import numpy as np          # not needed

class Dice:
    def roll(self):
        return randint(1, 6)

frequencies = [0]*13        # array to hold results of dice roll 
                            # will use frequencies 2 to 12)

dice = Dice()
remaining_rolls = 10000     # number of remaining rolls 
while remaining_rolls > 0:
    roll = dice.roll() + dice.roll() # roll sum
    frequencies[roll] += 1   # increment array at index roll by 1
    remaining_rolls -= 1
    
print(frequencies)

输出

[0, 0, 272, 583, 829, 1106, 1401, 1617, 1391, 1123, 863, 553, 262]

使用列表理解 作为 while 循环的替代方法

frequencies = [0]*13 
for roll in [dice.roll() + dice.roll() for _ in range(10000)]:
    frequencies[roll] += 1
print(frequencies) # Simpler Output

说明

作业:

frequencies = [0]*13

创建一个包含 13 个元素的数组,索引从 0 到 12 最初用零填充。

每次掷骰子的总和是 2 到 12 之间的数字(即 11 个值)

要增加滚动计数,我们使用:

 frequencies[roll] += 1

这是 syntactic sugar 用于:

frequencies[roll] = frequencies[roll] + 1

例如,如果 roll = 5,我们将频率加 1[5] 这会增加掷骰次数为 5 的计数。

两个 bin 始终为零:

frequencies[0] and frequencies[1]

这是因为 2 <= roll <= 12 所以我们从不增加 bin 0 和 1。