作业20200325

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}的形式
def read_user_info(file_path):

    k_list = ['name', 'sex', 'age', 'salary']

    with open(file_path, 'rt', encoding='utf8') as f:

        return [{k:v for k, v in zip(k_list, item.strip().split())} for item in f]


if __name__ == '__main__':

    res = read_user_info('user_info.txt')
    for item in res:
        print(item)

2 根据1得到的列表,取出所有人的薪资之和
3 根据1得到的列表,取出所有的男人的名字
4 根据1得到的列表,将每个人的信息中的名字映射成首字母大写的形式
5 根据1得到的列表,过滤掉名字以a开头的人的信息

def read_user_info(file_path):

    k_list = ['name', 'sex', 'age', 'salary']

    with open(file_path, 'rt', encoding='utf8') as f:
        user_list = [{k: int(v) if k in ['age', 'salary'] else v  for k, v in zip(k_list, item.strip().split())} for item in f]


    return user_list

if __name__ == '__main__':

    res = read_user_info('user_info.txt')
    print(res)

    # 2
    total_salary = sum(item.get('salary') for item in res)
    # print(total_salary)

    # 3
    male_name_list = [item['name'] for item in res if item['sex'] == 'male']
    # print(male_name_list)

    # 4
    new_res = [{k: v.capitalize() if type(v) is str else v for k, v in item.items()} for item in res]
    # print(new_res)

    # 5
    new_res2 = [item for item in res if not item.get('name').startswith('a')]
    # print(new_res2)
   

6 使用递归打印斐波那契数列(前两个数的和得到第三个数,如:0 1 1 2 3 4 7...)

def fibo(n):

    if n <= 1:
        return n
    else:
        return(fibo(n-1) + fibo(n-2))


for i in range(10):
    res = fibo(i)
    print(res)

7 一个嵌套很多层的列表,如l=[1,2,[3,[4,5,6,[7,8,[9,10,[11,12,13,[14,15]]]]]]],用递归取出所有的值

def get_item(li):
    for item in li:
        if isinstance(item, list):
            get_item(item)
        else:
            print(item)


if __name__ == '__main__':
    
    l=[1,2,[3,[4,5,6,[7,8,[9,10,[11,12,13,[14,15]]]]]]]
    get_item(l)
posted @ 2020-03-25 18:38  the3times  阅读(31)  评论(0)    收藏  举报