我是編程新手,我正在嘗試創建一個隨機數迭代器,它將接受 numpy 隨機范圍并計算 1-10 中每個數字出現的次數。示例:隨機范圍從 1 到 5,它將計算 # 出現的次數。count1 出現一次,count2 出現 3 次,count 9 出現一次。代碼:import numpy as npx1 = np.random.random(10)count1 = 0count2 = 0count3 = 0count4 = 0count5 = 0count6 = 0count7 = 0count8 = 0count9 = 0 count10 = 0for x in range(1,x1): if x == 1: count1 += count1 elif x == 2: count2 += count2 elif x == 3: count3 += count3 elif x == 4: count4 += count4 elif x == 5: count5 += count5 elif x == 6: count6 += count6 elif x == 7: count7 += count7 elif x == 8: count8 += count8 elif x == 9: count9 += count9 elif x == 10: count10 += count10 print(count1) print(count2) print(count3) print(count4) print(count5) print(count6) print(count7) print(count8) print(count9) print(count10)
1 回答

精慕HU
TA貢獻1845條經驗 獲得超8個贊
你的代碼有“countX += countX”并且這兩個都是零 - 所以你總是只是將零加在一起。你想要“countX += 1”。
對于您的打印,請使用 print(str(countX)) 并確保不縮進(不確定上面是否只是格式化)
但除此之外,我認為這段代碼并沒有實現您所尋找的目標。您只需選擇 1 到 10 之間的一個數字,然后從 1 循環到比該數字小 1 的數字并進行計數。例如,如果您的隨機數是 5,您的結果將是:1 1 1 1 0 0 0 0 0 0。
您想要定義運行循環的次數并在循環中每次隨機化數字
添加回答
舉報
0/150
提交
取消