编程题练习
第一题:打印如下格式
题目
#(‘2017-03-13 11:50:09’, 271, 131),
#(‘2017-03-14 10:52:19’, 273, 131),
#(‘2017-03-13 11:50:19’, 271, 126),
#(签到时间,课程id,人员id)
格式:
‘’’
{
131: [
{‘lessonid’: 271, ‘checkintime’: ‘2017-03-13 11:50:09’},
{‘lessonid’: 273, ‘checkintime’: ‘2017-03-14 10:52:19’},
],
126: [
{‘lessonid’: 271, ‘checkintime’: ‘2017-03-13 11:50:19’},
],
}
‘’’
(‘2017-03-13 11:50:09’, 271, 131),
(‘2017-03-13 11:50:19’, 271, 126),
(‘2017-03-13 11:50:25’, 271, 85),
(‘2017-03-13 11:50:31’, 271, 118),
(‘2017-03-13 11:50:34’, 271, 119),
‘’’
dict2={}
with open('d:/name松勤测试/0907编程题一.txt') as f:
# print(f.read())
for one in f.read().splitlines():
# print(one.replace('(','').replace(')',''))
one1=one.replace('(','').replace(')','').strip().replace("'",'') #左右括号都去掉。‘替换成空字符
# print(one1)
one2=one1.strip(',') # 去掉最后的逗号
# print (one2)
citime,lessonid,studentid=one2.split(',')
# print(citime)
# print(studentid) #有空格,需要去掉
lessonid=int(lessonid.strip())
studentid=studentid.strip()
dict1={'checkintime':citime,'lessonid':lessonid,}
print(dict1)
if studentid not in dict2:
dict2[studentid]=[] #把studentid放进去,在的话这句话不执行
dict2[studentid].append(dict1) #新建
print(dict2)
import pprint
pprint.pprint(dict2)
第二题:打印符合要求的格式
题目:
name:Jake ;salary :12000
name :Mike ;salary : 12300
name:Divina; salary: 86600
打印格式如下后
name: Jake ; salary: 12000 ; tax: 1200 ; income: 10800
name: Mike ; salary: 12300 ; tax: 1230 ; income: 11070
name: Divina ; salary: 86600 ; tax: 8660 ; income: 77940
写入file2文件中
with open ('d:/file1.txt') as f1,open('d:/file2.txt','w+')as f2:
lines=f1.read().splitlines() #读取文件中的内容,并且以行位单位,生成一个列表
# print(lines)
for one in lines: #遍历刚才生成的列表,比如第一个元素是'name: Jack ; salary: 12000'
# print(one)
a,b=one.split(';') #以;号为分隔符将元素'name: Jack ; salary: 12000'分为两个值,然后用两个变量来接收这两个值
# print(a)
name=a.split(':')[1].strip() #对分出来的a再次切割,'name: Jack ',取出名字Jack
salary=int(b.split(':')[1].strip()) #对分出来的b再次切割' salary: 12000',取出工资的数值12000
# print(f'name:{name:<7};salary:{salary:>7};tax:{salary*0.1:>4};income:{salary*0.9:>7}')
f2.write(f'name: {name:<7}; salary:{salary:>7} ; tax: {int(salary*0.1):>4} ; income:{int(salary*0.9):>7}\n')
#转成int防止有小数点,记得换行
第二题:统计10000以内,含有多少个有3的数字
使用:列表生成式