Python:在创建随机数字后,我如何将这些数字与我制作的列表相关联

所以基本上我需要创建一个标记为[0,1,2,3,4,5,10,25,100 ]。然后我需要在(0.75到4.75)+3之间创建随机数。现在我需要打印一些东西,如“缓冲区3和平均值为x秒”。 x将是生成的随机数。每个缓冲区必须有它自己的随机数Python:在创建随机数字后,我如何将这些数字与我制作的列表相关联

def main(): 

buffer= [0,1,2,3,4,5,10,25,100]

time= random.uniform(0.75,4.75)+3

sum=0

for i in range (1, 500):

sum = sum + time;

average= sum/1500

for buffer in range(0,1,2,3,4,5,10,25,100):

print("For Buffer",buffer,",the average time is",average,".")


[解决]

#Lab 1 using python. 

Import random #Importing random number generator.

def main():

buffers= [0,1,2,3,4,5,10,25,100]; #Defining the buffers using list.

for buffer in buffers:

sum=0;

for i in range (1, 500): # Create a loop which will create random number and increment 500 times.

time= (random.uniform (0.75,4.75))+3

sum = sum + time

average= sum/500; #Finding the average of each buffers random numbers.

print("For Buffer",buffer,",the average time is",average,"."); #Print the output.

回答:

你只需要改变它,你的平均计算在你的循环中完成。

buffer= [0,1,2,3,4,5,10,25,100] 

for buffer in range(0,1,2,3,4,5,10,25,100):

sum=0

for i in range (1, 500):

time= random.uniform(0.75,4.75)+3

sum = sum + time;

average= sum/1500

print("For Buffer",buffer,",the average time is",average,".")

回答:

您可以将每个缓冲区与其平均值相关联,使用一个字典使用缓冲区直接作为键和值的平均值。

def main(): 

buffer= [0,1,2,3,4,5,10,25,100]

time= random.uniform(0.75,4.75)+3

sum=0

dict_of_buffers = {}

for i in range (1, 500):

sum = sum + time;

average= sum/1500

for buffer in range(0,1,2,3,4,5,10,25,100):

print("For Buffer",buffer,",the average time is",average,".")

dict_of_buffers[buffer] = average

以上是 Python:在创建随机数字后,我如何将这些数字与我制作的列表相关联 的全部内容, 来源链接: utcz.com/qa/263156.html

回到顶部