【发布时间】:2020-10-14 17:30:49
【问题描述】:
我正在编写这个非常简单的代码来了解 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 的任何数字(来自滚动两个骰子)都会出现。
【问题讨论】:
标签: python arrays numpy for-loop counting