资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

Python传递列表的方法-创新互联

创新互联www.cdcxhl.cn八线动态BGP香港云服务器提供商,新人活动买多久送多久,划算不套路!

成都创新互联成立于2013年,是专业互联网技术服务公司,拥有项目网站设计制作、成都网站制作网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元望城做网站,已为上家服务,为望城各地企业和个人服务,联系电话:18982081108

这篇文章将为大家详细讲解有关Python传递列表的方法,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

传递列表

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传递列表的方法-创新互联
文章位置:http://cdkjz.cn/article/hcpdd.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220