计算 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的任何数字(滚动两个骰子(都会出现。

对代码进行简单修改,以获取滚动值计数。如果你特别想利用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 loop 的替代方案

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

这是的语法糖

frequencies[roll] = frequencies[roll] + 1

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

两个仓位始终为零:

frequencies[0] and frequencies[1]

这是因为2<=滚动<=12,所以我们从不递增bin 0和1。

最新更新