按值将列表传递给函数 [英] Pass list to function by value

查看:62
本文介绍了按值将列表传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按值将列表传递给函数.默认情况下,列表和其他复杂对象通过引用传递给函数.这是一些目标:

I want to pass a list into function by value. By default, lists and other complex objects passed to function by reference. Here is some desision:

def add_at_rank(ad, rank):
    result_ = copy.copy(ad)
    .. do something with result_
    return result_

这个可以写得更短吗?换句话说,我不想改变广告.

Can this be written shorter? In other words, I wanna not to change ad.

推荐答案

您可以使用 [:],但是对于包含列表(或其他可变对象)的列表,您应该使用 copy.deepcopy():

You can use [:], but for list containing lists(or other mutable objects) you should go for copy.deepcopy():

lis[:] 等价于 list(lis)copy.copy(lis),并返回一个浅拷贝列表.

lis[:] is equivalent to list(lis) or copy.copy(lis), and returns a shallow copy of the list.

In [33]: def func(lis):
    print id(lis)
   ....:     

In [34]: lis = [1,2,3]

In [35]: id(lis)
Out[35]: 158354604

In [36]: func(lis[:])
158065836

何时使用deepcopy():

In [41]: lis = [range(3), list('abc')]

In [42]: id(lis)
Out[42]: 158066124

In [44]: lis1=lis[:]

In [45]: id(lis1)
Out[45]: 158499244  # different than lis, but the inner lists are still same

In [46]: [id(x) for x in lis1] = =[id(y) for y in lis]
Out[46]: True

In [47]: lis2 = copy.deepcopy(lis)  

In [48]: [id(x) for x in lis2] == [id(y) for y in lis]  
Out[48]: False

这篇关于按值将列表传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆