如何使该程序“美丽”? [关闭]

问题描述 投票:0回答:1

请参考以下代码:

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)语句使代码看起来非常难看。任何改善它的想法将不胜感激。

python
1个回答
0
投票

您可以将结果存储在词典中:

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
© www.soinside.com 2019 - 2024. All rights reserved.