请参考以下代码:
import numpy as np
def MakeRandomFlag():
a = np.random.randint(1,5, size=10)
return a[3]
Type1=0
Type2=0
Type3=0
Type4=0
Type5=0
for i in range(10):
CollectResult = MakeRandomFlag()
if(CollectResult == 1):
Type1+=1
if(CollectResult == 2):
Type2+=1
if(CollectResult == 3):
Type3+=1
if(CollectResult == 4):
Type4+=1
if(CollectResult == 5):
Type5+=1
print(Type0,Type1,Type2,Type3,Type4)
我感觉到很多if(CollectResult == 1)语句使代码看起来非常难看。任何改善它的想法将不胜感激。
您可以将结果存储在词典中:
results = {1:0, 2:0, 3:0, 4:0, 5:0}
for i in range(10):
c = MakeRandomFlag()
if c in results:
results[c] += 1