作业day17
2020-06-23
1、文件a.txt内容如下,标题为:姓名,性别,年纪,薪资
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', 'r', encoding='utf-8') as f: l = [] for line in f: dic = {} name, sex, age, salary = line.strip('\n').split(" ") dic['name'] = name dic['sex'] = sex dic['age'] = int(age) dic['salary'] = int(salary) l.append(dic) print(l)
2、根据1得到的列表,取出薪资最高的人的信息
info1 = max(l ,key = lambda i: i["salary"]) print(info1)
3、根据1得到的列表,取出最年轻的人的信息
info2 = min(l, key = lambda i: i['age']) print(info2)
4、根据1得到的列表,取出所有人的薪资之和
all_salaries = sum([item['salary'] for item in l]) print(all_salaries)
5、根据1得到的列表,取出所有的男人的名字
name_male = [item['name'] for item in l if item['sex'] == 'male'] print(name_male)
6、根据1得到的列表,将每个人的信息中的名字映射成首字母大写的形式
for item in l: item['name'] = item['name'].capitalize() print(l)
7、根据1得到的列表,过滤掉名字以a开头的人的信息
new_l = [item for item in l if not item['name'].startswith('a')] print(new_l)
8、将names=['egon','alex_sb','wupeiqi','yuanhao']中的名字全部变大写
names = ['egon', 'alex_sb', 'wupeiqi', 'yuanhao'] new_names = [name.upper() for name in names] print(new_names)
9、将names=['egon','alex_sb','wupeiqi','yuanhao']中以sb结尾的名字过滤掉,然后保存剩下的名字长度
names = ['egon', 'alex_sb', 'wupeiqi', 'yuanhao'] name_length = [len(name) for name in names if not name.endswith('sb')] print(name_length)
10、求文件a.txt中最长的行的长度(长度按字符个数算,需要使用max函数)
with open('info.txt', mode='r', encoding='utf-8') as f: length = [len(line) for line in f] res = max(length)
print(res)
11、求文件a.txt中总共包含的字符个数?思考为何在第一次之后的n次sum求和得到的结果为0?(需要使用sum函数)
length = [] with open('a.txt', mode='r', encoding='utf-8') as f:
length = [len(line) for line in f]
print(sum(length))
12、思考题
with open('a.txt') as f:
g=(len(line) for line in f)
print(sum(g)) #为何报错?
print(sum(g))应该写进文件操作里面,不应该写在顶级
13、文件shopping.txt内容如下
mac,20000,3
lenovo,3000,10
tesla,1000000,10
chicken,200,1
求总共花了多少钱?
打印出所有商品的信息,格式为[{'name':'xxx','price':333,'count':3},...]
l1 = [] with open('shopping.txt') as f: for line in f: name, price, count = line.strip('\n').split(',') dic = {} dic['name'] = name dic['price'] = int(price) dic['count'] = int(count) l1.append(dic) print(l1) money = sum([item['price'] * item['count'] for item in l1]) print(money)
14、使用递归打印斐波那契数列(前两个数的和得到第三个数,如:0 1 1 2 3 4 7...)
def func(a, b): print(a + b, end=' ') if b > 10000: return func(b, a + b) func(0, 1)
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 func1(l): for i in l: if type(i) is list: func1(i) else: print(i) func1(l)