Python传递列表的方法

发布时间:2020-08-06 11:08:54 作者:小新
来源:亿速云 阅读:183

这篇文章将为大家详细讲解有关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传递列表的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. Python如何实现传递列表副本方式
  2. python嵌套列表的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:如何解决电脑总是跳出垃圾广告的问题

下一篇:怎么设置电脑安装权限

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》