运行程序超过x次

时间:2013-10-02 23:01:43

标签: python

我正在尝试编写一个调用函数的函数(roll die(),它会将一个骰子滚动1000次并依赖于列表[1,2,3,4,5,6],因此结果可能是[ 100,200,100,300,200,100])并告诉它运行x次。好像我的代码一遍又一遍地打印x次

#simulate rolling a six-sided die multiple tiems, and tabulate the results using a list
import random  #import from the library random so you can generate a random int
def rollDie(): 
    #have 6 variables and set the counter that equals 0
    one = 0  
    two = 0
    three = 0
    four = 0
    five = 0
    six = 0
    #use a for loop to code how many times you want it to run
    for i in range(0,1000):
        #generate a random integer between 1 and 6
        flip = int(random.randint(1,6))
        # the flip variable is the the number you rolled each time
        #Every number has its own counter
        #if the flip is equal to the corresponding number, add one
        if flip == 1:
            one = one + 1
        elif flip == 2:
            two = two + 1
        elif flip == 3:
            three = three + 1
        elif flip == 4:
            four = four + 1
        elif flip == 5:
            five = five + 1
        elif flip == 6:
            six = six + 1
        #return the new variables as a list
    return [one,two,three,four,five,six]

我遇到问题的新功能是:

def simulateRolls(value):
    multipleGames = rollDie() * value
    return multipleGames

如果您输入4表示值

,我希望看到这样的结果
[100,300,200,100,100,200]
[200,300,200,100,100,100]
[100,100,100,300,200,200]
[100,100,200,300,200,100]

有人可以指导我朝正确的方向发展吗?

2 个答案:

答案 0 :(得分:1)

你可以得到你想要的东西:

def simulateRolls(value):
    multipleGames = [rollDie() for _ in range(value)]
    return multipleGames

顺便说一下,你原来的功能似乎完全正常,但是如果你感兴趣的话,你可以删除一些像这样的冗余:

def rollDie(): 
    #have 6 variables and set the counter that equals 0
    results = [0] * 6

    #use a for loop to code how many times you want it to run
    for i in range(0,1000):
        #generate a random integer between 1 and 6
        flip = int(random.randint(1,6))
        # the flip variable is the the number you rolled each time
        results[flip - 1] += 1

    return results

答案 1 :(得分:1)

该行

multipleGames = rollDie() * value

将评估rollDie()一次并将结果乘以value

相反,请重复拨打value次。

return [rollDie() for i in xrange(value)]

您还可以通过使用

中的列表来简化rollDie功能
import random  #import from the library random so you can generate a random int
def rollDie(): 
    result = [0] * 6
    for i in range(0,1000):
        result[random.randint(0,5)] += 1
    return result