Python 地图有链吗?

发布于 2024-11-01 13:18:34 字数 377 浏览 2 评论 0原文

在Python中,可以使用itertools.chain以惰性方式扩展列表:

L = itertools.chain(L1, L2)

是否有惰性映射“粘合”运算符?即,

M = glue(M1, M2)

其中

M['blah']

返回

M1['blah'] if 'blah' in M1 else M2['blah']

and,M 具有适当的 keys()values() 生成器。

In Python, it's possible to extend a list in a lazy way by using itertools.chain:

L = itertools.chain(L1, L2)

Is there a lazy map "gluing" operator? I.e.,

M = glue(M1, M2)

where

M['blah']

returns

M1['blah'] if 'blah' in M1 else M2['blah']

and, M has appropriate generators for keys() and values().

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

枕头说它不想醒 2024-11-08 13:18:34

Python 3.3 添加了 collections.ChainMap 来实现这一点。

Python 3.3 added collections.ChainMap that does exactly that.

音盲 2024-11-08 13:18:34

构建一个类来表示针对映射列表的惰性求值,并根据您的应用程序定制行为是很简单的。例如:

from UserDict import DictMixin

class Map(object, DictMixin):
    def __init__(self, *maps):
        self.maps = maps
    def __getitem__(self, key):
        for m in self.maps:
            if key in m:
                return m[key]
    def keys(self):
        return list(self.iterkeys())
    def iterkeys(self):
        return (k for m in self.maps for k in m.iterkeys())
    def values(self):
        return list(self.itervalues())
    def itervalues(self):
        return (v for m in self.maps for v in m.itervalues())

def glue(*maps):
    return Map(*maps)

M1 = {'blah': 1}
M2 = {'duh': 2}

M = glue(M1, M2)
print M['blah']
print M['duh']
print list(M.keys())
print list(M.values())

输出:

1
2
['blah', 'duh']
[1, 2]

It's straightforward to build a class to represent lazy evaluations against a list of maps, and tailor the behavior to your application. For example:

from UserDict import DictMixin

class Map(object, DictMixin):
    def __init__(self, *maps):
        self.maps = maps
    def __getitem__(self, key):
        for m in self.maps:
            if key in m:
                return m[key]
    def keys(self):
        return list(self.iterkeys())
    def iterkeys(self):
        return (k for m in self.maps for k in m.iterkeys())
    def values(self):
        return list(self.itervalues())
    def itervalues(self):
        return (v for m in self.maps for v in m.itervalues())

def glue(*maps):
    return Map(*maps)

M1 = {'blah': 1}
M2 = {'duh': 2}

M = glue(M1, M2)
print M['blah']
print M['duh']
print list(M.keys())
print list(M.values())

Output:

1
2
['blah', 'duh']
[1, 2]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文