1

我正在尝试编写一个调用函数的函数(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]

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

4

2 回答 2

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
于 2013-10-02T23:09:52.470 回答
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
于 2013-10-02T23:06:35.457 回答