1.傳遞列表
可以將列表當(dāng)做參數(shù)傳給函數(shù)轿塔,使用函數(shù)來(lái)處理數(shù)據(jù)更高效特愿。
def greet_users(names):
for name in names:
msg="hello, "+name.title()
print(msg)
usernames=['hannah','ty','margot']
greet_users(usernames)
2.在函數(shù)中修改列表
將列表傳給函數(shù)后嗎,函數(shù)就可以修改列表勾缭,且這種修改是永久性的揍障。
#創(chuàng)建一個(gè)列表,包含要打印的設(shè)計(jì)
unprinted_designs=['iphone case','robotpendant','dodecahedron']
#創(chuàng)建一個(gè)空列表俩由,顯示已完成打印的設(shè)計(jì)
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個(gè)函數(shù)'''
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.禁止函數(shù)修改列表
在調(diào)用函數(shù)時(shí)毒嫡,將列表的副本傳遞給函數(shù),這樣函數(shù)對(duì)列表所做的修改只是影響副本而不會(huì)影響到原來(lái)的列表幻梯。
但如果不是非必要兜畸,還是傳遞列表而非列表的副本,因?yàn)閯?chuàng)建列表副本需要時(shí)間成本碘梢,尤其是列表含有大量數(shù)據(jù)時(shí)咬摇。
調(diào)用函數(shù)時(shí),傳遞列表的副本:function_name(list_name[:])
切片表示法[:]創(chuàng)建列表的副本煞躬。
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=[]
#在調(diào)用函數(shù)時(shí)肛鹏,傳遞列表副本給函數(shù)
make_magicians(magicians[:])
show_magicians(magicians)
show_magicians(magicians_edited)
4.傳遞任意數(shù)量的實(shí)參
有時(shí)預(yù)先不知道函數(shù)需要接受多少個(gè)實(shí)參,結(jié)合*傳遞任意數(shù)量實(shí)參恩沛。
一個(gè)號(hào)表示創(chuàng)建一個(gè)空元組:def function_name(list_name)
#*topping中的*號(hào)讓python 創(chuàng)建一個(gè)名為toppings的空元組在扰,并將收到的所有值都封裝到這個(gè)元組中。
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')
兩個(gè)號(hào)創(chuàng)建一個(gè)空字典: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)