gpt4 book ai didi

python - 与主函数同名的辅助函数?

转载 作者:太空宇宙 更新时间:2023-11-04 00:55:08 25 4
gpt4 key购买 nike

在处理 Intro to data analysis 时关于 Udacity 的类(class)我偶然发现了以下内容。在编写下面的函数时,我没有意识到我将辅助函数 standardize(series) 命名为与主函数 standardize(df) 相同。令我惊讶的是,该功能运行良好。

当我在 df.apply(standardize) 中使用它时,解释器如何知道要使用哪个版本的标准化函数?它与参数的类别(系列与 df)有什么关系吗?为什么它不尝试使用递归?或者,即使是这样,我似乎也无法概念化这是如何一步步实现的。

grades_df = pd.DataFrame(
data={'exam1': [43, 81, 78, 75, 89, 70, 91, 65, 98, 87],
'exam2': [24, 63, 56, 56, 67, 51, 79, 46, 72, 60]},
index=['Andre', 'Barry', 'Chris', 'Dan', 'Emilio',
'Fred', 'Greta', 'Humbert', 'Ivan', 'James']
)
def standardize(df):
'''
Fill in this function to standardize each column of the given
DataFrame. To standardize a variable, convert each value to the
number of standard deviations it is above or below the mean.
'''
def standardize(series):
return (series - series.mean())/series.std(ddof = 0)
return df.apply(standardize)

standardize(grades_df)

最佳答案

要回答“解释器如何知道要使用哪个版本的标准化函数...”,它基于语言中的范围规则。

在大多数语言中,名称(函数、变量等的标识符)首先从本地范围解析,如果找不到,则进入下一个外部级别,等等。

在这种情况下,“标准化”函数有两个定义——第一个是在解释器的全局范围内定义的,第二个是在第一个范围内定义的。当您调用 df.apply(standardize) 时,名称“standardize”被解析为本地定义的函数(第二个),因为在查看外部范围之前先搜索本地范围。

关于python - 与主函数同名的辅助函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35467064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com