我用代码生成了 1 到 100 之间的 100 个随机数:
def histogram():
for x in range(100):
x = random.randint(1, 100)
print(x)
Run Code Online (Sandbox Code Playgroud)
现在我试图用直方图表示这些信息,我将 matplotlib.pyplot 导入为 plt 并尝试构建它,但我似乎遇到了问题。
我试过:
def histogram():
for x in range(100):
x = random.randint(1, 100)
return x
histogram_plot = histogram()
plt.hist(histogram_plot)
plt.show()
Run Code Online (Sandbox Code Playgroud)
我也尝试过:
def histogram():
for x in range(100):
x = random.randint(1, 100)
print(x)
plt.hist(x)
plt.show()
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
这是一个与您的代码类似的小工作示例
>>> import matplotlib.pyplot as plt
>>> import random
>>> data = [random.randint(1, 100) for _ in range(100)]
>>> plt.hist(data)
(array([ 15., 13., 9., 9., 11., 9., 9., 11., 6., 8.]),
array([ 1. , 10.9, 20.8, 30.7, 40.6, 50.5, 60.4, 70.3, 80.2, 90.1, 100. ]),
<a list of 10 Patch objects>)
>>> plt.show()
Run Code Online (Sandbox Code Playgroud)
您遇到的问题在于您的histogram职能。您每次迭代都会将变量重新分配x给随机变量int,而不是构建list随机值。
| 归档时间: |
|
| 查看次数: |
10044 次 |
| 最近记录: |