微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将常量传递给函数

如何解决如何将常量传递给函数

在以下情况下哪个是更好的设计,为什么?

A:

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)

B:

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','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','com2'])

添加了基于@MisterMiyagi答案的C版本。

注意1:在这种情况下,stop_words是固定的,不会改变。

注意2:stop_words可以是一个很小的列表,也可以是一个很大的列表。

解决方法

中间立场:对参数使用默认值。

arm-buildroot-linux-gnueabihf

现在常数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']) 仅创建一次(定义函数时);它不会污染全球范围;并且如果您最终想要,可以在致电{'com1','com2'}时选择传递不同的stop_words

,

首选在全局范围内创建常量。全局范围一次评估 ,而局部函数范围一次评估每个函数调用

对于非常大的搜索,由于其O(1)查找而不是set O(n)查找,因此更喜欢使用list。预期为constants should be named with ALL_CAPS_NAMES的值。函数应直接引用常量 iff ,这些常量不打算被替换。

STOP_WORDS = {'com1','com2'}  # constant set of words
    
def clean_text(text_tokens):
    return [token for token in text_tokens if token not in STOP_WORDS]
    #                             directly access constant ^

clean_text(['hello','com2'])

对于小的常量,将它们作为文字提供可能是有利的。甚至CPython都能将内联文字优化为实际常量。

def clean_text(text_tokens):
    return [
        token
        for token in text_tokens
        if token not in {'com1','com2'}
        #               ^ compiled as LOAD_CONST (frozenset({'com2','com1'}))
    ]

clean_text(['hello','com2'])

当前的优化器将listtuple常量转换为tuple常量,并将setfrozenset常量转换为frozenset常量

,

如果您想在每次调用函数时将stop_words作为参数传递不同的列表,则方案A更好,而方案B仅对['com1','com2']进行测试,这意味着您仅更改此列表当您编辑函数本身时。

结论:方案A更好地测试不同的列表,并将它们作为参数传递给函数。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。