亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

計算 numpy 數組(列表)中元素的出現次數

計算 numpy 數組(列表)中元素的出現次數

PHP
慕哥9229398 2023-11-09 15:47:09
我正在編寫這個非常簡單的代碼來學習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 wished1111111111# This is the Output from the loop and finally the print(count1)我想知道,如何存儲出現次數,從 2 到 12 的任何數字(來自擲兩個骰子)確實會出現。
查看完整描述

1 回答

?
慕斯709654

TA貢獻1840條經驗 獲得超5個贊

對代碼進行簡單修改即可獲取滾動值的計數。如果您特別想使用 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

這是語法糖:


frequencies[roll] = frequencies[roll] + 1

例如,如果 roll = 5,我們將頻率[5] 加 1,這會增加 roll 為 5 的次數的計數。


兩個 bin 始終為零:


frequencies[0] and frequencies[1]

這是因為 2 <= roll <= 12 所以我們永遠不會增加 bin 0 和 1。


查看完整回答
反對 回復 2023-11-09
  • 1 回答
  • 0 關注
  • 144 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號