可变数据类型:列表、字典
不可变数据类型:整型、浮点型、字符串、元组
为什么可变数据类型不能作为python函数的参数?请看以下例子:
def foo(a=[]): a.append(1) return a print(foo()) print(foo())
结果:
[1] [1,1函数的返回值的内存地址:(id(foo())) print(id(foo()))结果:
会发现我们每次返回的都是同一个对象。
再看下以下例子:
b = [1,2] def test(place=b): place.append(1 place (b) (test()) print(b)结果:
[1,2,1]当使用列表作为参数传入函数时,实际上是引用传递。也就是传入的是实际参数的地址,而place=b也就是指向相同的地址。比如以下的:
c = [1,3] d = c (id(c)) print(id(d))结果:
当我们修改d的值时,同样也会影响到c:
d.append(4) (d) (c) (id(d)) print(id(c))结果:
所以在上述中,通过在test()函数中修改place的值也会影响到b的值。
为什么会这样呢?
python中一切皆对象。函数也是对象,可以这么理解,一个函数是一个被它自己定义而执行的对,;默认参数是一种"成员数据",所以它们的状态和其他对象一样,会随着每一次调用而改变。
怎么避免这种现象呢?
使用以下方式:
None): if a is None: a = [] a.append(1] [1] [1]如果需要处理任意对象(包括None),则可以使用哨兵对象:
sentinel = object() def myfunc(value=sentinel): if value sentinel: value = expression # use/modify value here应用:求数组的全排列
最后我们来看一个应用例子:求数组的全排列
基本思路是回溯法:每次从数组中选一个值加入到tmp中,如果数组中没有值了,就将tmp加入到结果中,返回。
如果我们的代码是这种:
arr = [1,1)">] res = [] def permutation(arr,tmp=[]): global res if len(arr) == 0: res.append(tmp) return for i in range(len(arr)): tmp = tmp + [arr[i]] newArr = arr[:i]+arr[i+1:] permutation(newArr,tmp) subset(arr,tmp=[]) print(res)结果:
[[1,3],[1,2],1],1]]这里就出现了上述的情况,我们只需要简单的改以下即可:
arr = [1,1)"> range(len(arr)): newTmp = tmp +