gpt4 book ai didi

Python:嵌套循环的问题。想要多次运行随机变量并对结果求平均值......

转载 作者:太空宇宙 更新时间:2023-11-03 17:50:48 25 4
gpt4 key购买 nike

我尝试在 while 循环内使用 while 循环,但收效甚微。我们想从牌组变量中选择一个数字。每次选择 1 到 20 之间的数字时,选择变量都会增加。

然后我们想要运行该片段 100 次并对 type1 变量进行平均。最终结果应该是 1 到 7 之间的数字。任何帮助都会很棒!

import random
deck = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60]

a = 0
b = 0
type1 = 0

while b < 100:
while a < 7:
a += 1
selection = deck[random.randint(0,len(deck)-1)]
if selection > 0 and selection < 21:
print "success!"
type1 += 1
print type1
b += 1
print b

exit()

最佳答案

一些小问题,请参阅评论。

import random
# Use a list comprehension to make it more readable
deck = [x for x in range(1, 61)]
# Consider creating a length variable, so you aren't calculating len(deck) every loop
deck_length = len(deck)

a = 0
b = 0
type1 = 0

while b < 100:
while a < 7:
a += 1
selection = deck[random.randint(0,deck_length-1)]
if selection > 0 and selection < 21:
print("success!")
type1 += 1
print type1
# Move this increment into the while loop, so that it gets updated.
b += 1
print b

exit()

关于Python:嵌套循环的问题。想要多次运行随机变量并对结果求平均值......,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29126311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com