JP1*_*992 4 python random list
我已经用零填充了已知长度的列表.我试图通过列表返回并在每个索引处放置0-1的随机浮点数.我正在使用while循环来执行此操作.但是,代码并没有输入随机数.列表仍然是零,我不明白为什么.我插入了一个print语句,它告诉我列表仍然是零.我将不胜感激任何帮助!
randomList = [0]*10
index = 0
while index < 10:
randomList[index] = random.random()
print("%d" %randomList[index])
index = index + 1
Run Code Online (Sandbox Code Playgroud)
列表是随机的:
>>> randomList
[0.46044625854330556, 0.7259964854084655, 0.23337439854506958, 0.4510862027107614, 0.5306153865653811, 0.8419679084235715, 0.8742117729328253, 0.7634456118593921, 0.5953545552492302, 0.7763910850561638]
Run Code Online (Sandbox Code Playgroud)
但是你将它的元素作为itegers打印出来"%d" % randomList[index],所以所有这些值都舍入到零.您可以使用"%f"格式化程序来打印浮点数:
>>> print("%.5f" % randomList[index])
0.77639
Run Code Online (Sandbox Code Playgroud)
>>> print("{.5f}".format(randomList[index]))
0.77639
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
265 次 |
| 最近记录: |