Skip to main content
 首页 » 编程设计

python之Defaultdict 和 constant_factory 与 lambda

2024年10月25日10kenshinobiy

documentation为 defaultdict (from collections) 提供了一个例子:

A faster and more flexible way to create constant functions is to use itertools.repeat() which can supply any constant value (not just zero):

def constant_factory(value): 
    return itertools.repeat(value).next 
d = defaultdict(constant_factory('<missing>')) 
d.update(name='John', action='ran') 
 
'%(name)s %(action)s to %(object)s' % d 
>>>'John ran to <missing>' 

这似乎行得通,但这样做也是如此:

d = defaultdict(lambda: '<missing>') 
d.update(name='John', action='ran') 
 
'%(name)s %(action)s to %(object)s' % d 
>>>'John ran to <missing>' 

最后一个版本对我来说似乎更紧凑、更清晰。是否有明确的速度或内存或可维护性(或任何其他)原因来定义 constant_factory 而不是使用 lambda 函数?我在一些将由其他人使用(和维护)的代码中使用它,所以我想确保我不只是按照自己的喜好玩游戏。

请您参考如下方法:

itertools.repeat(value).next 比 lambda 函数快得多。这是因为 lambda 函数执行 python 字节码,而 itertools 原语是在 C 中实现的。