zoukankan      html  css  js  c++  java
  • python函数参数中带有默认参数list的坑

    在python中函数参数中如果带有默认参数list遇到问题

    先看一段代码

    def f(x,l=[]):
        for i in range(x):
            l.append(i*i)
        print(l)
    
    print('---1---')
    f(4)
    print('---2---')
    f(5)

    执行结果:

    ---1---
    [0, 1, 4, 9]
    ---2---
    [0, 1, 4, 9, 0, 1, 4, 9, 16]

    预期的结果为:

    ---1---
    [0, 1, 4, 9]
    ---2---
    [0, 1, 4, 9, 16]
    

    问题解释:当定义函数时,会保存函数中默认参数list的值,也就是列表[],在每次调用的时候如果传递了列表,则使用传递的列表,没有传递,使用定义函数时保存的默认参数list,以上案例中两次调用都没有传递默认参数list,程序会调用定义函数时,保存的默认参数list,列表在append的时候回在原来的基础上添加,所以会产生以上结果,我们可以通过打印id看出。

    修改代码:

    def f(x,l=[]):
        print(id(l))  # 添加打印id
        for i in range(x):
            l.append(i*i)
        print(l)
    
    
    print('---1---')
    f(4)
    print('---2---')
    f(5)
    

    结果:

    ---1---
    140306123906248
    [0, 1, 4, 9]
    ---2---
    140306123906248
    [0, 1, 4, 9, 0, 1, 4, 9, 16]
    

    会发现id值是相同的,说明两次执行时使用的都是定义函数时默认的参数

    再次修改代码:

    def f(x,l=[]):
        print(id(l))
        for i in range(x):
            l.append(i*i)
        print(l)
    
    
    print('---1---')
    f(4)
    print('---2---')
    f(5,[])
    print('---3---')
    f(6)

    结果:

    ---1---
    140017293614280
    [0, 1, 4, 9]
    ---2---
    140017293614472
    [0, 1, 4, 9, 16]
    ---3---
    140017293614280
    [0, 1, 4, 9, 0, 1, 4, 9, 16, 25]

    会发现执行传递空列表的函数时打印的id不一样,而没有传递的一样。当传递空list时函数体当中会使用传递的空list,没有传递时,使用函数默认的list。所以会产生以上结果

    如果想要达到预期的结果编写一下代码

    def f(x,l=None):
        if l is None:
            l = []
        for i in range(x):
            l.append(i*i)
        print(l)
    
    
    print('---1---')
    f(4)
    print('---2---')
    f(5)
    print('---3---')
    f(6)
    

    结果:

    ---1---
    [0, 1, 4, 9]
    ---2---
    [0, 1, 4, 9, 16]
    ---3---
    [0, 1, 4, 9, 16, 25]
    

     这样就达到了预期的结果  ------_<_>_------

  • 相关阅读:
    KL散度、JS散度和交叉熵
    np.dot()计算两个变量的乘积
    numpy 相关统计
    sns.FacetGrid(),map用法
    df.to_dict()转化为字典数据
    springboot 热部署
    Springboot thymeleaf
    springboot 静态资源
    springboot yaml part2
    Warning: You cannot set a form field before rendering a field associated with the value. ant desgin pro form 表单报错
  • 原文地址:https://www.cnblogs.com/kayb/p/7443264.html
Copyright © 2011-2022 走看看