汇总和打印随机数的更有效方法是什么?

时间:2018-08-08 08:36:23

标签: python

所以...代码完成了我想要的事情。尽管据我所知,这似乎效率很低,但有人告诉我它是无效的。本质上,我掷2个骰子,所以它的范围是2到12(分别加起来)。然后,我会计算是否要累加2、3、4,依此类推。看到我这样做的方式,我做了11个变量和11个if和elif语句,这是极其多余的,而且效率似乎很低。

我不知道如何提高效率,或者是否有更Python化的方法。

def distribution_of_rolls(amount: int) -> str:
    count2 = ''
    count3 = ''
    count4 = ''
    count5 = ''
    count6 = ''
    count7 = ''
    count8 = ''
    count9 = ''
    count10 = ''
    count11 = ''
    count12 = ''
        countList = [count2, count3, count4, count5, count6, count7, count8, count9, count10, count11, count12
]
resultStr = ''
for _ in range(amount):
    roll = roll2dice()
    if roll == 2:
        countList[0] += '*'
    elif roll == 3:
        countList[1] += '*'
    elif roll == 4:
        countList[2] += '*'
    elif roll == 5:
        countList[3] += '*'
    elif roll == 6:
        countList[4] += '*'
    elif roll == 7:
        countList[5] += '*'
    elif roll == 8:
        countList[6] += '*'
    elif roll == 9:
        countList[7] += '*'
    elif roll == 10:
        countList[8] += '*'
    elif roll == 11:
        countList[9] += '*'
    elif roll == 12:
        countList[10] += '*'

    for i in range(2, 13):
        resultStr += (str(i) + ':    ' + str(len(countList[i - 2])) + ' ' + countList[i - 2] + "\n")

    print(resultStr)
    distribution_of_rolls(200)

这是结果(没有问题,这就是我想要的):

2:    3 ***
3:    11 ***********
4:    17 *****************
5:    18 ******************
6:    22 **********************
7:    37 *************************************
8:    32 ********************************
9:    23 ***********************
10:    15 ***************
11:    14 **************
12:    8 ********

1 个答案:

答案 0 :(得分:2)

使用collections.Counter提高效率

>>> from collections import Counter
>>> c = Counter(roll2dice() for _ in range(200))
>>> for i in range(2,14):
        print (f'{i:2}:  {c[i]:2} {"*"*c[i]}')
... 
 2:  12 ************
 3:  20 ********************
 4:  13 *************
 5:  19 *******************
 6:  13 *************
 7:  20 ********************
 8:   9 *********
 9:  18 ******************
10:  15 ***************
11:  19 *******************
12:  22 **********************
13:  20 ********************