作业
作业:
1、文件内容如下,标题为:姓名,性别,年纪,薪资
egon male 18 3000
alex male 38 30000
wupeiqi female 28 20000
yuanhao female 28 10000
要求:
从文件中取出每一条记录放入列表中,
列表的每个元素都是{'name':'egon','sex':'male','age':18,'salary':3000}的形式
with open('a.txt', mode='rt', encoding='utf-8')as f:
items = (line.split() for line in f)
res = [{'name': name, 'gender': gender, 'age': age, 'salary': salary}
for name, gender, age, salary in items]
print(res)
2 根据1得到的列表,取出薪资最高的人的信息
print(max(res,key=lambda key:key['salary']))
3 根据1得到的列表,取出最年轻的人的信息
print(min(res,key=lambda key:key['age']))
4 根据1得到的列表,取出所有人的薪资之和
salarys = sum(int(dic["salary"]) for dic in res)
print(salarys)
5 根据1得到的列表,取出所有的男人的名字
males = [dic["name"]for dic in res if dic["gender"] == "male"]
print(males)
6 根据1得到的列表,将每个人的信息中的名字映射成首字母大写的形式
for dic in res:
dic["name"] = dic["name"].title()
print(res)
7 根据1得到的列表,过滤掉名字以a开头的人的信息
res1=filter(lambda item:item['name'].startswith('a'),res)
print(list(res1))
8、将names=['egon','alex_sb','wupeiqi','yuanhao']中的名字全部变大写
names=['egon','alex_sb','wupeiqi','yuanhao']
print([name.upper() for name in names])
9、将names=['egon','alex_sb','wupeiqi','yuanhao']中以sb结尾的名字过滤掉,然后保存剩下的名字长度
print([name for name in names if name.endswith('_sb')])
10、求文件a.txt中最长的行的长度(长度按字符个数算,需要使用max函数)
with open('a.txt', 'rt', encoding='utf-8')as f:
print(max(len(line) for line in f))
11、求文件a.txt中总共包含的字符个数?思考为何在第一次之后的n次sum求和得到的结果为0?(需要使用sum函数)
with open('a.txt','rt',encoding='utf-8')as f:
print(sum(len(line) for line in f))
12、思考题
with open('a.txt') as f:
g=(len(line) for line in f)
print(sum(g)) #为何报错?
缩进问题
13、文件shopping.txt内容如下
mac,20000,3
lenovo,3000,10
tesla,1000000,10
chicken,200,1
求总共花了多少钱?
打印出所有商品的信息,格式为[{'name':'xxx','price':333,'count':3},...]
with open('a.txt', mode='rt', encoding='utf-8')as f:
items = (line.split(',') for line in f)
res = [{'name': name,'price':price,'num':num}
for name,price,num in items]
print(res)
14、使用递归打印斐波那契数列(前两个数的和得到第三个数,如:0 1 1 2 3 4 7...)
def func(a, b, stop):
if a > stop:
return
print(a, end=' ')
func(b, a + b, stop)
func(0, 1, 10000)
15、一个嵌套很多层的列表,如l=[1,2,[3,[4,5,6,[7,8,[9,10,[11,12,13,[14,15]]]]]]],用递归取出所有的值
l =[1, 2, [3, [4, 5, 6, [7, 8, [9, 10, [11, 12, 13, [14, 15]]]]]]]
def func(seq):
for item in seq:
if type(item) is list:
func(item)
else:
print(item)
func(l)

浙公网安备 33010602011771号