Python如何传递列表
【摘要】传递列表defgreet_users(names): fornameinnames: mag="Hello,"+name title()+"!" print(mag) user_names=[& 39;hannah& 39;,& 39;bob& 39;
传递列表
def greet_users(names):
for name in names:
mag = "Hello, " + name.title() + "!"
print(mag)
user_names = ['hannah', 'bob', 'margot']
greet_users(user_names)
运行结果:
Hello, Hannah!
Hello, Bob!
Hello, Margot!
1. 在函数中修改列表
# 创建一个列表,其中包含一些要打印的设计
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
# 模拟打印每个设计,直到没有未打印的设计为止,打印后移至completed_models中
while unprinted_designs:
current_design = unprinted_designs.pop()
# 模拟根据设计制作打印模型的过程
print("Printing model: " + current_design)
completed_models.append(current_design)
# 显示打印好的模型
print("nThe following models have been printed:")
print(completed_models)
运行结果:
Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone case
The following models have been printed:
['dodecahedron', 'robot pendant', 'iphone case']
用函数如何表达上述代码的意思呢?
def print_models(unprinted_designs, completed_models):
while unprinted_designs:
current_design = unprinted_designs.pop()
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)
当print_models函数调用之后,列表completed_models已经不是最初定义的空,所有列表unprinted_designs中的元素已转移至列表completed_models,接下来调用show_completed_models函数就将列表completed_models中的元素都打印出来。
2. 禁止函数修改列表
上述的例子中print_models函数调用之后,列表unprinted_designs中的元素均已移除,此时的列表为空。但若想保留列表中的元素呢?
print_models(unprinted_designs[:], completed_models)
用切片法 [ : ] 创建列表副本,函数调用时使用的是列表的副本,而不是列表本身,此时函数中对列表做的修改不会影响到列表unprinted_designs。
上一篇:python入门基础教程
下一篇:Python中的返回值是什么
就业培训申请领取
环球青藤
官方QQ群扫描上方二维码或点击一键加群,免费领取大礼包,加群暗号:青藤。 一键加群
最新文章
Python编程各地入口
环球青藤官方微信服务平台
刷题看课 APP下载
免费直播 一键购课
代报名等人工服务
Python编程热点排行