xiximayou

可变数据类型:列表、字典

不可变数据类型:整型、浮点型、字符串、元组

为什么可变数据类型不能作为python函数的参数?请看以下例子:

def foo(a=[]):
  a.append(1)
  return a
print(foo())
print(foo())
print(foo())

结果:

[1]
[1, 1]
[1, 1, 1]

我们继续打印下每次函数的返回值的内存地址:

print(id(foo()))
print(id(foo()))
print(id(foo()))

结果:

140344852133960
140344852133960
140344852133960

会发现我们每次返回的都是同一个对象。

再看下以下例子:

b = [1,2]
def test(place=b):
  place.append(1)
  return place
print(b)
print(test())
print(b)
print(test())
print(b)

结果:

[1, 2]
[1, 2, 1]
[1, 2, 1]
[1, 2, 1, 1]
[1, 2, 1, 1]

当使用列表作为参数传入函数时,实际上是引用传递。也就是传入的是实际参数的地址,而place=b也就是指向相同的地址。比如以下的:

c = [1,2,3]
d = c
print(id(c))
print(id(d))

结果:

140344851860104
140344851860104

当我们修改d的值时,同样也会影响到c:

d.append(4)
print(d)
print(c)
print(id(d))
print(id(c))

结果:

[1, 2, 3, 4]
[1, 2, 3, 4]
140344851860104
140344851860104

所以在上述中,通过在test()函数中修改place的值也会影响到b的值。

为什么会这样呢?

python中一切皆对象。函数也是对象,可以这么理解,一个函数是一个被它自己定义而执行的对,;默认参数是一种"成员数据",所以它们的状态和其他对象一样,会随着每一次调用而改变。

怎么避免这种现象呢?

使用以下方式:

def foo(a=None):
  if a is None: 
    a = []
  a.append(1)
  return a
print(foo())
print(foo())
print(foo())

结果:

[1]
[1]
[1]

如果需要处理任意对象(包括None),则可以使用哨兵对象:

sentinel = object()
 
def myfunc(value=sentinel):
    if value is sentinel:
        value = expression
    # use/modify value here

应用:求数组的全排列

最后我们来看一个应用例子:求数组的全排列

基本思路是回溯法:每次从数组中选一个值加入到tmp中,如果数组中没有值了,就将tmp加入到结果中,返回。

如果我们的代码是这种:

arr = [1,2,3]
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, 2, 3], [1, 2, 3, 2], [1, 2, 1, 3], [1, 2, 1, 3, 1], [1, 2, 3, 1, 2], [1, 2, 3, 1, 2, 1]]

这里就出现了上述的情况,我们只需要简单的改以下即可:

arr = [1,2,3]
res = []
def permutation(arr,tmp=[]):
  global res
  if len(arr) == 0:
    res.append(tmp)
    return
  for i in range(len(arr)):
    newTmp = tmp + [arr[i]]
    newArr = arr[:i]+arr[i+1:]
    permutation(newArr,newTmp)
subset(arr,tmp=[])
print(res)

结果:

[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

我们只需要每次新建一个列表即可。

 

参考:https://blog.csdn.net/rommi/article/details/51979556

相关文章: