1. 文件内容
标题为:姓名,性别,年纪,薪资
egon male 18 3000
alex male 38 30000
wupeiqi female 28 20000
yuanhao female 28 10000
操作
# 1.从文件中取出每一条记录放入列表中,列表的每个元素都是{'name':'egon','sex':'male','age':18,'salary':3000}的形式
list1 = []
with open(r'db.txt', mode='rt', encoding='utf-8') as f:
for line in f:
line_dic = {}
name, sex, age, salary = line.strip().split(' ')
line_dic['name'] = name
line_dic['sex'] = sex
line_dic['age'] = age
line_dic['salary'] = salary
list1.append(line_dic)
print(list1)
with open(r'db.txt', mode='rt', encoding='utf-8') as f1:
dic_list = [{'name': list2[0], 'sex': list2[1], 'age': list2[2], 'salary': list2[3]} for list2 in
[line.strip().split(' ') for line in f1]]
print(dic_list)
# 2.根据1得到的列表,取出所有人的薪资之和
a = sum(int(i['salary']) for i in list1)
print(a)
salary_sum = [int(dic['salary']) for dic in list1]
print(sum(salary_sum))
# 3、根据1得到的列表,取出所有的男人的名字
list3 = [list1_dic['name'] for list1_dic in list1 if list1_dic['sex'] == 'male']
print(list3)
# 4、根据1得到的列表,将每个人的信息中的名字映射成首字母大写的形式
list_capitalize = [{'name': i['name'].capitalize(), 'sex': i['sex'], 'age': i['age'], 'salary': i['salary']} for i in
list1]
print(list_capitalize)
# 5、根据1得到的列表,过滤掉名字以a开头的人的信息
list4 = [i for i in list1 if not i['name'].startswith('a')]
print(list4)
2. 使用递归打印斐波那契数列(前两个数的和得到第三个数,如:0 1 1 2 3 4 7...)
def func(x,y):
print(x)
if x > 100:
return
x, y = y, x+y
func(x,y)
func(0,1)
3. 一个嵌套很多层的列表,如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(list1):
for i in list1:
if type(i) is list:
func(i)
else:
print(i)
func(l)