python - 在函数python中定义一个函数好不好

标签 python

这是我在项目中写的代码。

python写哪个比较好?

def get_list_of_university_towns():
    ....
    def parse_state(item):
        return re.sub('\[edit\]', '', item)
    uni_towns['State'] = uni_towns['State'].apply(parse_state)
    return uni_towns

或者:

def parse_state(item):
    return re.sub('\[edit\]', '', item)
def get_list_of_university_towns():
    ....
    uni_towns['State'] = uni_towns['State'].apply(parse_state)
    return uni_towns

这个“parse_state(item)”函数只在“get_list_of_university_towns()”中被调用一次,并且永远不会被再次使用。我个人认为在函数中定义它会更容易理解。但是,我在别人的项目中几乎看不到这种代码。

那么,这段代码应该怎么写呢?

最佳答案

在函数内写函数是Pythonic吗

是的,是的。实际上,为了不污染模块命名空间,在内部执行比在外部执行更符合 Pythonic。

这段代码应该怎么写?

在其他函数中带有函数定义的选项有效。另一种 Pythonic 方式是使用匿名 lambda 函数:

def get_list_of_university_towns():
    ....
    uni_towns['State'] = uni_towns['State'].apply(lambda item: re.sub('\[edit\]', '', item))
    return uni_towns

优化

正如所建议的那样,现在你说它是 Pandas 的数据帧,这意味着该函数将被多次调用,你应该编译表达式或使用 str.replace() 而不是 re.sub():

def get_list_of_university_towns():
    ....
    uni_towns['State'] = uni_towns['State'].apply(lambda item: item.replace('[edit]', ''))
    return uni_towns

关于python - 在函数python中定义一个函数好不好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46789427/

相关文章:

python - 在 Jinja(Django) 中使用字典索引显示列表元素

python - 如何在另一个列表的前面插入一个列表?

Python 3 从网络解析 PDF

python - Python 中的模糊查找

python - 由 <function check_errors.<locals>.wrapper at 0x03A69780> 启动的线程中出现未处理的异常

Python CGIHTTPServer 为动态页面和静态页面设置文件类型

python - 按索引选择不同形状的numpy数组并将其写回

python - MSBUILD : error MSB3428: Could not load the Visual C++ component "VCBuild.exe"

python - 在 Django 之外使用 Django 数据库层?

python - 如何让它更像 Pythonic?