Python编程:从入门到实践第八章读书笔记8.4传递列表
#coding:gbk
#greeter_users.py
def greeter_users(names):
"""向列表中的每位用户都发出简单的问候"""
for name in names:
msg = "Hello, " + name.title() + "!"
print(msg)
greeter_users(['hannah','ty','margot'])
#8.4.1在函数中修改列表
#printing_models.py
#首先创建一个列表,其中包含一些要打印的设计
unprinted_designs = ['iphone case','robot pendant', 'dodecachedron']
completed_designs = []
#模拟打印每个设计,知道没有未打印的设计为止
# 打印每个设计后,都将其移到列表completed_models中
while unprinted_designs:
current_design = unprinted_designs.pop()
#模拟根据设计制作3D打印模型的过程
print("Printing model: " + current_design)
completed_designs.append(current_design)
# 显示打印好的所有模型
print("\nThe following models have been printed: ")
for completed_design in completed_designs:
print(completed_design)
#重新组织
def print_models(unprinted_designs, completed_models):
"""
模拟打印每个设计,直到没有未打印的设计为止
"""
while unprinted_designs:
current_design = unprinted_designs.pop()
#模拟根据设计制作3D打印模型的过程
print("Printing model: " + current_design)
completed_models.append(current_design)
def show_completed_models(completed_models):
"""显示打印好的所有模型"""
print("\nThe following models have been printed: ")
for completed_model in completed_models:
print(completed_model)
unprinted_designs = ['iphone case','robot pendant','dodecahedron']
completed_models = []
print_models(unprinted_designs[:],completed_models)
show_completed_models(completed_models)
#8.4.2进制函数修改列表
#要将列表的副本传递给函数,可像如下所做:
# function_name(list_name[:])
#print_models(unprinted_designs[:],completed_models)
#虽然向函数传递列表的副本可保留原始列表的内容,但除非有充分的理由需要传递副本,否则还是应该将原始列表传递给函数,
#因为让函数使用现成列表可避免花时间和内存创建副本,从而提高效率,在处理大型列表时尤其如此
哎函数好难