从创建的列表中绘图

时间:2013-02-23 00:14:56

标签: python python-2.7 matplotlib

考虑代码:

a = [1, 2, 3, 4]
for i in range(len(a)):

   for j in range(i+1, len(a)):
       dd21 = (a[i]-a[j])
       j = j + 1
       if i != j and dd21 !=0:
             print i, j, dd21
fig = plt.figure()
ax = fig.add_subplot(111)

ax.hist(dd21)
plt.tight_layout()

plt.tight_layout()
plt.show()

output = IndexError: invalid index to scalar variable.

我需要更改dd21的列表才能在直方图中进行绘图?

1 个答案:

答案 0 :(得分:1)

您似乎打算在循环中存储计算的所有dd21值。 但是,目前您每次都会覆盖dd21

这应该可以使它工作,允许你绘制直方图:

a = [1, 2, 3, 4]
dd21 = [] # initialize empty list
for i in range(len(a)):

   for j in range(i+1, len(a)):
       dd21.append(a[i]-a[j])
       # ... continue as before