为什么python3函数的默认值在函数被多次调用时被覆盖?

2024-06-16 13:56:16 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能解释一下为什么当我多次调用这个函数时,L在默认情况下从未设置为空?但是,任何后续调用的结果都是将L附加到前面调用的所有结果之后?在

函数将数据分成7天的块,从最后一个日期([::-1])开始, 计算每7天的平均值,并将结果作为值附加到 名单。忽略不完整的块

数据的默认值是顺序格式的日期列表。在

def separate(data = [i for i in w][::-1],L = []):
    print("separate has been called, data is %s and L is %s" % (data, L))

    if len(data)<7:
        return L

    total = 0
    dates = 0

    for value in data[:7]:
        if w[value] != "None":
            total += float(w[value])
            dates += 1
    L.append(total / dates)

    return separate(data[7:], L)

Tags: 数据函数infordatareturnifis
1条回答
网友
1楼 · 发布于 2024-06-16 13:56:16

取自the documentation

The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes.

[...]

If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:

def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L

相关问题 更多 >