双向/反向映射 [英] Two way/reverse map

查看:35
本文介绍了双向/反向映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 python 做这个交换机的事情,我需要跟踪谁在和谁说话,所以如果 Alice --> Bob,那么这意味着 Bob --> Alice.

是的,我可以填充两个哈希图,但我想知道是否有人想用一个来实现.

或者建议另一种数据结构.

没有多个对话.假设这是针对客户服务呼叫中心的,因此当 Alice 拨入总机时,她只会与 Bob 通话.他的回复也只发给她.

解决方案

您可以通过子类化 dict 并添加所需的逻辑来创建自己的字典类型.这是一个基本示例:

class TwoWayDict(dict):def __setitem__(self, key, value):# 使用这些值删除任何以前的连接如果键入 self:del self[key]如果自我价值:del self[值]dict.__setitem__(self, key, value)dict.__setitem__(self, value, key)def __delitem__(self, key):dict.__delitem__(self, self[key])dict.__delitem__(self, key)def __len__(self):"""返回连接数"""return dict.__len__(self)//2

它是这样工作的:

<预><代码>>>>d = TwoWayDict()>>>d['foo'] = 'bar'>>>d['foo']'酒吧'>>>d['bar']'富'>>>借)1>>>del d['foo']>>>d['bar']回溯(最近一次调用最后一次):文件<stdin>",第 7 行,在 <module> 中.键错误:'酒吧'

我确定我没有涵盖所有情况,但这应该会让您开始.

I'm doing this switchboard thing in python where I need to keep track of who's talking to whom, so if Alice --> Bob, then that implies that Bob --> Alice.

Yes, I could populate two hash maps, but I'm wondering if anyone has an idea to do it with one.

Or suggest another data structure.

There are no multiple conversations. Let's say this is for a customer service call center, so when Alice dials into the switchboard, she's only going to talk to Bob. His replies also go only to her.

解决方案

You can create your own dictionary type by subclassing dict and adding the logic that you want. Here's a basic example:

class TwoWayDict(dict):
    def __setitem__(self, key, value):
        # Remove any previous connections with these values
        if key in self:
            del self[key]
        if value in self:
            del self[value]
        dict.__setitem__(self, key, value)
        dict.__setitem__(self, value, key)

    def __delitem__(self, key):
        dict.__delitem__(self, self[key])
        dict.__delitem__(self, key)

    def __len__(self):
        """Returns the number of connections"""
        return dict.__len__(self) // 2

And it works like so:

>>> d = TwoWayDict()
>>> d['foo'] = 'bar'
>>> d['foo']
'bar'
>>> d['bar']
'foo'
>>> len(d)
1
>>> del d['foo']
>>> d['bar']
Traceback (most recent call last):
  File "<stdin>", line 7, in <module>
KeyError: 'bar'

I'm sure I didn't cover all the cases, but that should get you started.

这篇关于双向/反向映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆