INFILE是一個家譜:Python的while循環問題
holla 1755
ronaj 1781
asdflæj 1803
axle 1823
einar 1855
baelj 1881
æljlas 1903
jobbi 1923
gurri 1955
kolli 1981
Rounaj 2004
我想從INFILE和我想的平均最終打印出每一代人的時間。在這裏,我想我的問題是,line2
失控的範圍時INFILE結束:
def main():
infile = open('infile.txt', 'r')
line = infile.readline()
tmpstr = line.split('\t')
age=[]
while line !='':
line2 = infile.readline()
tmpstr2 = line2.split('\t')
age.append(int(tmpstr2[1]) - int(tmpstr[1]))
print age
tmpstr = tmpstr2
infile.close()
print sum(age)*1./len(age)
main()
所以我決定閱讀所有信息列表,但tmpstr
doesn't變化值這裏:
def main():
infile = open('infile.txt', 'r')
line = infile.readline()
age=[]
while line !='':
tmpstr = line.split('\t')
age.append(tmpstr[1])
print age
infile.close()
print sum(age)*1./len(age)
main()
怎麼來的?這兩個腳本有什麼問題?爲什麼我兩次寫main()
? 任何想法如何解決這兩個問題?
感謝名單全部,這是它是如何結束:
def main():
with open('infile.txt', 'r') as input:
ages = []
for line in input:
data = line.split()
age = int(data[1])
ages.append(age)
gentime = []
for i in xrange(len(ages)-1):
print ages[i+1] - ages[i]
gentime.append(ages[i+1] - ages[i])
print 'average gentime is', sum(gentime)*1./len(gentime)
main()
我的建議是去[codereview.se]代替。 – 2012-01-14 23:20:27
@Martin:codereview.SE不適用於破損的代碼。 – 2012-01-14 23:23:43
@NiklasBaumstark:好的,好點。我以前沒有這樣想過。 – 2012-01-14 23:26:42