代码应该从 .txt 文件中读取逗号分隔值,根据否定性排序到数组中,然后绘制数据时遇到问题。这是代码,后跟 2 个 .txt 文件,第一个有效,但第二个无效
#check python is working
print "hello world"
#import ability to plot and use matrices
import matplotlib.pylab as plt
import numpy as np
#declare variables
posdata=[]
negdata=[]
postime=[]
negtime=[]
interestrate=.025
#open file
f= open('/Users/zacharygastony/Desktop/CashFlow_2.txt','r')
data = f.readlines()
#split data into arrays
for y in data:
w= y.split(",")
if float(w[1])>0:
postime.append(int(w[0]))
posdata.append(float(w[1]))
else:
negtime.append(int(w[0]))
negdata.append(float(w[1]))
print "Inflow Total: ", posdata
print "Inflow Time: ", postime
print "Outflow Total: ", negdata
print "Outflow Time: ", negtime
#plot the data
N=len(postime)
M=len(negtime)
ind = np.arange(N+M) # the x locations for the groups
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(ind, posdata+negdata, width, color='r')
# add some
ax.set_ylabel('Cash Amount')
ax.set_title('Cash Flow Diagram')
ax.set_xlabel('Time')
plt.plot(xrange(0,M+N))
plt.show()'
.txt 1_ _ ____
0,3761.97
1,-1000
2,-1000
3,-1000
4,-1000
.txt 2_ _ __ _ _
0,1000
1,-1000
2,1000
3,-1000
我的错误如下:
>>> runfile('/Users/zacharygastony/cashflow.py', wdir=r'/Users/zacharygastony')
hello world
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/zacharygastony/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 540, in runfile
execfile(filename, namespace)
File "/Users/zacharygastony/cashflow.py", line 24, in <module>
if float(w[1])>0:
IndexError: list index out of range