这是我在项目中写的代码。
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/