Python嵌套循环问题

时间:2015-03-19 14:14:12

标签: python loops for-loop while-loop

我正在尝试学习Python,我正在编写一些脚本以方便习惯该语言。

我正在尝试创建一个将滚动3'骰子'的脚本,如果所有3都返回6,它会将其写入列表,否则再次滚动并更新计数器。

这一切都应该发生很多次,这样我就可以得到一个大的列表,然后计算得到三倍的平均卷数。

经过多次迭代后,这是我的代码(可能是次优的,因为我编辑了很多东西试图找到一种工作方式)

    #!/usr/bin/python

from random import randint

first = randint(0,5)
second = randint(0,5)
third = randint(0,5)
count = 1
list = []

for_list =  range(10000)

for item in for_list:
        while first != 5 or second != 5 or third != 5:
                count+=1
                first = randint(0,5)
                second = randint(0,5)
                third = randint(0,5)
                if first == 5 and second == 5 and third == 5:
                        list.append(count)
                        count = 1
print sum(list) / float(len(list))

print list

现在看起来像while循环一样,但我无法弄清楚如何让它实际运行多次(for循环,在这个例子中10,000次)。

这是我的输出(打印“平均值”和列表,包含计数变量:

218.0
[218]

所以在这次运行中它花了218卷。之后脚本结束。 任何人都可以帮助我理解为什么脚本没有运行for循环吗?

谢谢!

2 个答案:

答案 0 :(得分:4)

你的布尔条件是错误的:

first != 5 or second != 5 or third != 5

如果所有三个值都设置为False,那么这只是5。当您找到三重套装时,while循环始终将为False

因此,在找到您的第一场比赛后,从那里开始,firstsecondthird变量设置为5while循环永远不会进入你的for循环迭代的其他9999次。

不要在这里使用while循环,只需使用大量迭代并在每次迭代时掷骰子,然后使用简单的if将其添加到列表中:

results = []
counter = 0

for iteration in xrange(10 ** 6):  # 1 million times
    counter += 1
    roll = random.randint(1, 6), random.randint(1, 6), random.randint(1, 6)
    if roll == (6, 6, 6):
        results.append(counter)
        counter = 0

我为结果列表使用了更好的名称;您希望避免使用与变量的内置类型相同的名称。由于您使用的是Python 2,我还转而使用xrange();没有必要建立一个完整的整数列表,只是为了控制循环重复的次数。

我用一个元组来存储三个骰子卷,并从1到6中选取数字以匹配传统的骰子数。然后,您可以通过与3个数字的另一个元组进行比较来测试是否找到匹配。

演示:

>>> results = []
>>> counter = 0
>>> for iteration in xrange(10 ** 6):  # 1 million times
...     counter += 1
...     roll = random.randint(1, 6), random.randint(1, 6), random.randint(1, 6)
...     if roll == (6, 6, 6):
...         results.append(counter)
...         counter = 0
... 
>>> sum(results, 0.0) / len(results)
217.40704500978472
>>> len(results)
4599

答案 1 :(得分:1)

经过一些修改,我相信这可能是你想要的:

from random import randint

first = randint(0,5)
second = randint(0,5)
third = randint(0,5)
count = 1
list = []

for_list = 10001
completed = 0

while completed < for_list:
    completed = completed+1
    count=count+1
    first = randint(0,5)
    second = randint(0,5)
    third = randint(0,5)
    if first == 5 and second == 5 and third == 5:
        list.append(count)
        count = 1

print sum(list) / float(len(list))

print list

返回了哪个;

172.071428571 [214, 196, 44, 14, 43, 31, 427, 179, 427, 48, 134, 78, 261, 256, 36, 242, 244, 40, 189, 53, 140, 690, 26, 802, 39, 45, 2, 93, 30, 26, 351, 117, 455, 24, 190, 359, 83, 23, 60, 81, 38, 3, 173, 205, 175, 689, 233, 59, 26, 122, 263, 415, 211, 38, 94, 100]

编辑:正如Martijn Pieters(下文)所说,你可以删除

first = randint(0,5)
second = randint(0,5)
third = randint(0,5)

来自循环外部。

相关问题