Vamei博客地址:http://www.cnblogs.com/vamei/archive/2012/07/19/2600135.html#!comments
请看Vamei博客下面别人的跟帖!
有一个record.txt的文档,内容如下:
# name, age, score
tom, 12, 86
Lee, 15, 99
Lucy, 11, 58
Joseph, 19, 56
第一栏为姓名(name),第二栏为年纪(age),第三栏为得分(score)
现在,写一个Python程序,
1)读取文件
2)打印如下结果:
得分低于60的人都有谁?
谁的名字以L开头?
所有人的总分是多少?
3)姓名的首字母需要大写,该record.txt是否符合此要求? 如何纠正错误的地方?
下面贴上我认为比较写的比较好的:
1.za花生树写的:
info = None with open('test.txt','rb') as fs: info = [eachline.strip(' ').split(',') for eachline in fs if not eachline.startswith('#')] print [item[0] for item in info if int(item[2]) < 60] print [item[0] for item in info if item[0].startswith('L')] print sum(int(item[2]) for item in info) if filter(lambda x:x[0][0].lower() == x[0][0],info): with open('new.txt','wb') as fd: fd.write(' '.join([','.join([item[0][0].upper()+item[0][1:],item[1],item[2]]) for item in info]))
#coding=utf8 class UserRecord(object): def __init__(self, name, age, score): self.name = name self.age = int(age) self.score = int(score) def __str__(self): return "%s, %d, %d" % (self.name, self.age, self.score) if __name__ == '__main__': info = [UserRecord(*(line.split(', '))) for line in file('record.txt') if line.strip() and not line.startswith('#')] print "得分低于60的人都有谁? ",' '.join([x.name for x in info if x.score < 60]) print "谁的名字以L开头? ",' '.join([y.name for y in info if y.name.startswith('L')]) print "所有人的总分是多少? ",sum([z.score for z in info]) print "姓名的首字母需要大写,该record.txt是否符合此要求? ",all([x.name.istitle() for x in info]) for x in info: x.name = x.name.capitalize() open('record2.txt','w').writelines(" ".join(map(str, info)))