【发布时间】:2020-12-20 08:10:34
【问题描述】:
在以下场景中哪一个是更好的设计,为什么?
答:
stop_words = ['com1', 'com2']
def clean_text(text_tokens, stop_words):
return [token for token in text_tokens if token not in stop_words]
clean_text(['hello', 'world', 'com1', 'com2'], stop_words)
乙:
def clean_text(text_tokens):
stop_words = ['com1', 'com2']
return [token for token in text_tokens if token not in stop_words]
clean_text(['hello', 'world', 'com1', 'com2'])
C:
STOP_WORDS = ['com1', 'com2']
def clean_text(text_tokens):
return [token for token in text_tokens if token not in STOP_WORDS]
clean_text(['hello', 'world', 'com1', 'com2'])
根据@MisterMiyagi 的回答添加了 C 版本。
注意1:在这种情况下,stop_words 是固定的,不会改变。
注意 2:stop_words 可以是一个很小的列表,也可以是一个很大的列表。
【问题讨论】:
-
如果它没有改变,你不需要它的参数。如果您想面向未来,请使用 A 和
stop_words=Noneanfif stop_words is None: stop_words = ['com1', 'com2'] -
要完成,还有“中间”的做法:默认参数:
clean_text(text_tokens, stop_words=['com1', 'com2']):。它不会污染全局范围,但表达式只计算一次。考虑在问题中将其设为 D 选项:-)
标签: python python-3.x pep8