美文网首页
Python:函数与列表、任意数量的实参

Python:函数与列表、任意数量的实参

作者: 庭阶 | 来源:发表于2020-04-19 15:35 被阅读0次

1.传递列表

可以将列表当做参数传给函数,使用函数来处理数据更高效。

def greet_users(names):
    for name in names:
        msg="hello, "+name.title()
        print(msg)
usernames=['hannah','ty','margot']
greet_users(usernames)

2.在函数中修改列表

将列表传给函数后吗,函数就可以修改列表,且这种修改是永久性的。

#创建一个列表,包含要打印的设计
unprinted_designs=['iphone case','robotpendant','dodecahedron']
#创建一个空列表,显示已完成打印的设计
completed_models=[]


while unprinted_designs:
    current_design=unprinted_designs.pop()
    print("Printing model is: "+current_design)
    completed_models.append(current_design)
print("the following models have been printed:")
for completed_model in completed_models:
    print(completed_model)



'''修改成2个函数'''
def print_models(unprinted_designs,completed_models):
    while unprinted_designs:
        current_design=unprinted_designs.pop()
        print("Printing model is: "+current_design)
        completed_models.append(current_design)
        
    
    
def show_models(completed_models):
    for completed_model in completed_models:
         print(completed_model)


unprinted_designs=['iphone case','robotpendant','dodecahedron']
completed_models=[]

print_models(unprinted_designs,completed_models)
show_models(completed_models)

3.禁止函数修改列表

在调用函数时,将列表的副本传递给函数,这样函数对列表所做的修改只是影响副本而不会影响到原来的列表。
但如果不是非必要,还是传递列表而非列表的副本,因为创建列表副本需要时间成本,尤其是列表含有大量数据时。

调用函数时,传递列表的副本:function_name(list_name[:])

切片表示法[:]创建列表的副本。

def show_magicians(magicians):
    for magician in magicians:
        print(magician) 

def make_magicians(magicians):
    for magician in magicians:
        magician='the Great '+magician
        magicians_edited.append(magician)

magicians=['mike','allen','tomy','amo']
magicians_edited=[]
#在调用函数时,传递列表副本给函数
make_magicians(magicians[:])
show_magicians(magicians)
show_magicians(magicians_edited)

4.传递任意数量的实参

有时预先不知道函数需要接受多少个实参,结合*传递任意数量实参。

一个号表示创建一个空元组:def function_name(list_name)

#*topping中的*号让python 创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中。
ef make_pizza(*toppings):
    print(toppings)

make_pizza('pepperoni')
make_pizza('mushrooms','pepperoni')


def make_pizza(*toppings):
    print("Making a pizza with the following toppings: ")
    for topping in toppings:
        print(toppings)

make_pizza('pepperoni')
make_pizza('mushrooms','pepperoni')

两个号创建一个空字典:def function_name(dictionary)

def build_profile(first,last,**user_info):
    profile={}
    profile['first_name']=first
    profile['last_name']=last
    for key,value in user_info.items():
        profile[key]=value
    return profile
user_profile=build_profile('albert','einstein',location='princeton',field='physics')
print(user_profile)

相关文章

网友评论

      本文标题:Python:函数与列表、任意数量的实参

      本文链接:https://www.haomeiwen.com/subject/skcivhtx.html