如何简化此代码

时间:2013-05-28 03:12:51

标签: python

我是初学者,我想知道是否有更简单的方法在Python中编写这个。我假设某种类型的字典,但我不明白如何写出来。 几天前我正在巡航,我玩掷骰子。我想知道赔率是否有些正确。所以,我写了这个,但我知道有一种更简单的方法。

import random

dice2 = 0
dice3 = 0
dice4 = 0
dice5 = 0
dice6 = 0
dice7 = 0
dice8 = 0
dice9 = 0
dice10 = 0
dice11 = 0
dice12 = 0

for i in range(100000):
            dice1 = random.randint(1,6)
            dice2 = random.randint(1,6)
            number = dice1 + dice2
            #print(dice1)
            if number == 2:
                        dice2 +=1
            elif number == 3:
                        dice3 += 1
            elif number == 4:
                        dice4 += 1
            elif number == 5:
                        dice5 += 1
            elif number == 6:
                        dice6 += 1
            elif number == 7:
                        dice7 += 1
            elif number == 8:
                        dice8 += 1
            elif number == 9:
                        dice9 += 1
            elif number == 10:
                        dice10 += 1
            elif number == 11:
                        dice11 += 1
            elif number == 12:
                        dice12 += 1

total = dice2+dice3+dice4+dice5+dice6+dice7+dice8+dice9+dice10+dice11+dice12

最后,它只打印出2-12的数字命中百分比。

3 个答案:

答案 0 :(得分:4)

我使用Counter作为它的用途:

from random import randint
from collections import Counter

counts = Counter(randint(1, 6) + randint(1, 6) for i in range(100000))
total = sum(counts.values())
number_of_tens = counts[10]

答案 1 :(得分:3)

from random import randint

dice = [0]*11
for i in range(100000):
    dice[randint(1,6)+randint(1,6)-2] += 1

total = sum(dice) #it is 100000, of course
for i, v in enumerate(dice, 2):
    print('{0}: {1}%'.format(i, v*100.0/total))

答案 2 :(得分:2)

import random

def roll(n=6):
    return random.randint(1, n)

dice = dict.fromkeys(range(2, 13), 0)

for i in range(100000):
    number = roll() + roll()
    dice[number] += 1

total = float(sum(dice.values()))
for k,v in dice.items():
    print "{}, {:.2%}".format(k, v/total)