Python如何传递列表
传递列表
<pre class="brush:php;toolbar:false">def greet_users(names): for name in names: mag = "Hello, " name.title() "!" print(mag) user_names = ['hannah', 'bob', 'margot'] greet_users(user_names)</pre>运行结果:
<pre class="brush:php;toolbar:false">Hello, Hannah! Hello, Bob! Hello, Margot!</pre>1. 在函数中修改列表
<pre class="brush:php;toolbar:false"># 创建一个列表,其中包含一些要打印的设计 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)</pre>运行结果:
<pre class="brush:php;toolbar:false">Printing model: dodecahedron Printing model: robot pendant Printing model: iphone case The following models have been printed: ['dodecahedron', 'robot pendant', 'iphone case']</pre>用函数如何表达上述代码的意思呢?
<pre class="brush:php;toolbar:false">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)</pre>当print_models函数调用之后,列表completed_models已经不是最初定义的空,所有列表unprinted_designs中的元素已转移至列表completed_models,接下来调用show_completed_models函数就将列表completed_models中的元素都打印出来。
2. 禁止函数修改列表
上述的例子中print_models函数调用之后,列表unprinted_designs中的元素均已移除,此时的列表为空。但若想保留列表中的元素呢?
<pre class="brush:php;toolbar:false">print_models(unprinted_designs[:], completed_models)</pre>用切片法 [ : ] 创建列表副本,函数调用时使用的是列表的副本,而不是列表本身,此时函数中对列表做的修改不会影响到列表unprinted_designs。
您可能感兴趣的文章:
python如何判断文件有多少行
Python如何传递列表
一文了解Python中的递归
进来吧,给自己10分钟,这篇文章带你直接学会python
python与java用途区别有哪些
谈谈Python中对象拷贝
python如何调用二维列表中的一维列表
Python 3.8 新功能大揭秘
python list怎么添加元素
Python之sys和argv详解