2013-12-22 140 views
4

我已經用零發起了一個已知長度的列表。我試圖回到列表中,並在每個索引處放置0-1的隨機浮點數。我正在使用while循環來做到這一點。但是,代碼並沒有放入隨機數字。該列表仍然充滿了零,我不明白爲什麼。我插入了一個打印語句,告訴我該列表仍然充滿零。我將不勝感激任何幫助!在python中創建隨機數列表

randomList = [0]*10 
index = 0 
while index < 10: 
    randomList[index] = random.random() 
    print("%d" %randomList[index]) 
    index = index + 1 

回答

7

名單是隨機的:

>>> randomList 
[0.46044625854330556, 0.7259964854084655, 0.23337439854506958, 0.4510862027107614, 0.5306153865653811, 0.8419679084235715, 0.8742117729328253, 0.7634456118593921, 0.5953545552492302, 0.7763910850561638] 

但你打印的元素itegers與"%d" % randomList[index],使所有這些值被四捨五入爲零。您可以使用 「%F」 格式打印浮點數:

>>> print("%.5f" % randomList[index]) 
0.77639 

'{:M:Nf}.format'

>>> print("{.5f}".format(randomList[index])) 
0.77639 
+0

或者只是'打印(randomList [指數])'。 – user2357112

4

你爲什麼不打印while後的名單?

...code... 
print randomList 

輸出

[0.5785868632203361, 0.03329788023131364, 0.06280615346379081, 0.7074893002663134, 0.6546820474717583, 0.7524730378259739, 0.5036483948931614, 0.7896910268593569, 0.314145366294197, 0.1982694921993332] 

如果YOUT希望你print聲明的工作,使用%f代替。

1
import random 
from pprint import pprint 

l = [] 

for i in range(1,11): 
    l.append(int(random.random() * (i * random.randint(1,1e12)))) 

pprint(l) 
2

列表理解更容易,更快速:

randomList = [random.random() for _ in range(10)]