我正在用 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) // 2And 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.
更多推荐
双向/反向映射
发布评论