Python函数——函数与列表、字典

1.传递列表

向函数传递的参数从普通的值变为了列表

def greet_people(names):
    for name in names:
        print(f"Hello, {name.title()}!")


usernames = ['hannah', 'ty', 'margot']
greet_people(usernames)

1.1在函数中修改列表

unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []
while unprinted_designs:
    current_design = unprinted_designs.pop()
    print(f"Printing model:{current_design}")
    completed_models.append(current_design)

print("\nThe following models have been printed:")
for completed_model in completed_models:
    print(completed_model)

用函数把功能分割

def print_models(unprinted_designs_fun, completed_models_fun):
    """
    模拟打印每个设计, 直到没有未打印的设计为止
    打印每个设计后, 都将其移到列表completed_models中
    """
    while unprinted_designs_fun:
        current_design_fun = unprinted_designs_fun.pop()
        print(f"Printing model:{current_design_fun}")
        completed_models_fun.append(current_design_fun)


def show_completed_models(completed_models_fun):  # 用来显示打印好的模型
    print("\nThe following models have been printed: ")
    for completed_model_fun in completed_models_fun:
        print(completed_model_fun)


unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []

print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)

1.2如何禁止函数修改列表
可以给函数传递一个副本使其不能改变原来的的列表

def greet_fun(name_list_fun):
    while name_list_fun:
        current_name = name_list_fun.pop()  # 这行代码将会破坏列表的完整性, 该怎么办呢?
        if current_name == '小琪':
            print(f"Hi! {current_name}. ", end=' ')
        else:
            print(f"Hello {current_name}.", end=' ')


name_list = ['小鸣', '小蛟', '小龙', '小恒', '小琪', '小卓', '小涵', '小平', '小庆']
greet_fun(name_list[:])  # 'name_list[:]'就是给'name_list'列表创建了一个副本避免了'name_list'被破坏
print(name_list)  # 仍然可以打印原来的列表

2.传递任意数量的实参

有时候并不知道要想函数传递多少个实参, 这时就可以使用下面的方法

def go_to_eat_hot_pot(*foods):  # 朋友们要带小鸣吃火锅但他们并不知道到底该点什么
    print(foods)


go_to_eat_hot_pot('No')  # 小鸣提议换成别的, 挨了朋友们一顿打
go_to_eat_hot_pot('牛肉卷', '羊肉卷', '虾滑', '面条', '菠菜')

'*'的作用是让python创建一个名为foods的空元组, 并将收到的所有值都封装到这个元组

2.1结合使用位置实参和任意数量的实参
这种任意实参的元组要排在普通实参的后面

def go_to_eat_hot_pot_again(people_number_fun, *foods_1):  # 如果要确定吃火锅的人数就要把关于人数的参数放在任意数量实参之前
    print(f"今天来的人数:{people_number_fun}, 决定吃:{foods_1}")


go_to_eat_hot_pot_again(0, "No! ")  # 小鸣又一次请求换别的吃, 又挨了一顿打
go_to_eat_hot_pot_again(9, '牛肉卷', '羊肉卷', '虾滑', '面条', '菠菜')

3.使用任意参数的关键字实参

上面的给形参前面加上*是使值存储到元组中, 下面的加两个‘*’号是给形参传递容量可变的字典

def build_profile(first, last, **people_info):
    people_info['first_name'] = first
    people_info['last_name'] = last
    return people_info


people_profile = build_profile('albert', 'einstein',  # profile [ˈprəʊfaɪl] n.面部侧影, 简介, 侧面轮廓, 概述
                              location='princeton',  # 这是键值对
                              fild='physics')  # 这也是键值对
print(people_profile)

当我们创建字典时, 但没想好它的内容可以用上面的方法
希望能帮到你

猜你喜欢

转载自blog.csdn.net/m0_46255324/article/details/115253443