一道python笔试题

巴扎黑
巴扎黑 原创
2020-09-03 15:34:54 2748浏览

下面这段代码:

# 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是否符合此要求? 如何纠正错误的地方?

#read lines from file
fobj = open('record.txt', 'r+')
print 'opened file: ', fobj.name
all_lines = fobj.readlines()
fobj.close()
lines = [l[:-1].split(', ') for l in all_lines if not l.startswith('#') and l.strip()]
#list person who's score less than 60
print [s[0] for s in lines if int(s[2]) < 60]
#list person who's name starts with 'L'
print [s[0] for s in lines if s[0].startswith('L')]
#compute the score of all person
print sum([int(s[2]) for s in lines])
#write new lines contains capitalize name into file
fobj = open('record2.txt', 'w+')
print 'opend file: ', fobj.name
newlines = []
for line in all_lines:
    if line[0].islower():
        line = line.capitalize()
    newlines.append(line)
print newlines
if newlines:
    fobj.writelines(newlines)
fobj.close()

相关文章推荐:《2020年python面试题汇总(最新)

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
上一条:Python2.7安装pydbg 下一条:python判断闰年