所以基本上我需要創建一個標記爲[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.
我不是你問這裏是什麼100%清楚,但如果你想爲每個緩衝區提供不同的隨機數,你需要或者移動隨機數生成*內*您緩衝區環,或者您需要將所有隨機數存儲在某個地方(例如列表),然後在您的緩衝區for循環中迭代該數字。 – jam 2013-02-26 15:18:47
爲什麼不'random.uniform(3.75,7.75)'? – Junuxx 2013-02-26 15:19:37