双向/反向映射

编程入门 行业动态 更新时间:2024-10-14 12:21:01
本文介绍了双向/反向映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在用 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.

更多推荐

双向/反向映射

本文发布于:2023-11-16 06:55:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1602005.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:双向

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!