如何在Python3中创建可重用或持久化的映射?

2024-04-26 17:37:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够做到,例如:

pmap = persistent_map(function, iterable(args))
foo = map(bar, pmap)
baz = map(bar, pmap) # right-hand side intentionally identical to that of the previous line.

解释器在使用pmap构造baz之前会知道重置pmap。你知道吗

我知道我可以将pmap的结果存储为tuplelist或其他结构(这是我在当前应用程序中所做的),但我不想这样做,因为可能会有1)巨大的存储需求(同时考虑副本)和2)不同的重新估值结果,当从动态文件生成iterable时。你知道吗

如果存在persistent_map的等价物,那么相应的内置特性或标准库特性是什么?或者,是否有第三方(希望可靠且随时可用)persistent_map等价物?如果现有的选项只有第三方,那么如何只使用内置的、可能的标准库特性来创建persistent_map?你知道吗

对于@MartijnPieters的评论,“这就是生成器的用途”,你是说有一种解决方案是这样的吗

def persistent_map(function, iterable):
    from functools import partial
    return partial(map, function, iterable)
foo = map(bar, pmap())
baz = map(bar, pmap())
# A toy example:
pmap = persistent_map(hex, range(3))
foo = map(len , pmap())
baz = map(hash, pmap())
print(*zip(pmap(), foo, baz))
('0x0', 3, 982571147) ('0x1', 3, 982571146) ('0x2', 3, 982571145)

Tags: rightmap标准foobarargsfunction特性