一必做题:
文件内容如下,标题为:姓名,性别,年纪,薪资
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}的形式
dict_list=[] with open('user.txt', 'rt', encoding='utf-8') as f: for line in f: dict = {} name,sex,age,salary=line.strip().split(' ') dict['name']=name dict['sex']=sex dict['age']=age dict['salary']=int(salary) dict_list.append(dict) print(dict_list)
2.根据1得到的列表,取出所有人的薪资之和
# sum_salary=0 # for line in dict_list: # sum_salary+=line['salary'] # print(sum_salary) sum_salary=sum([line['salary'] for line in dict_list]) print(sum_salary)
3.根据1得到的列表,取出所有的男人的名字
# for line in dict_list: # if line['sex']=='male': # print(line['name']) name_list=[line['name'] for line in dict_list if line['sex']=='male'] print(name_list)
4.根据1得到的列表,将每个人的信息中的名字映射成首字母大写的形式
for line in dict_list: line['name']=line['name'].title() print(line['name'])
5.根据1得到的列表,过滤掉名字以a开头的人的信息
new_list=[line for line in dict_list if not line['name'].startswith('A')] print(new_list) #for line in dict_list: # if not line['name'].startswith('A'): # print(line)
6.使用递归打印斐波那契数列(前两个数的和得到第三个数,如:0 1 1 2 3 4 7...)
def func(x,y): s=x+y print(x,end=" ") if y <= 100: func(y,s) func(0,1)
l=[1,2,[3,[4,5,6,[7,8,[9,10,[11,12,13,[14,15]]]]]]] def func(l): for x in l: if type(x) is list: #判断当前取出值如果是列表,则继续调用本身循环取值 func(x) else: print(x) func(l)