有没有更好的方式存储一个双语字典比存储其反向分离? [英] Is there a better way to store a twoway dictionary than storing its inverse separate?
问题描述
为key,value在someGenerator中:
myDict [key] = value
反向查找字典可以通过添加
invDict [value] = key
到为
循环。但这是一个Pythonic的方式吗?我应该写一个类Bijection(dict)
,它另外管理这个倒排的字典,并提供第二个查找功能?还是这样一个结构(或类似的一个)已经存在?
reverseict
函数,它将采用一个dict并返回相反的映射,如果我知道它是一对一的(抛出异常,看到相同的值两次)或值列表的键,如果不是。这样一来,每次我想要反向查找时,并不需要在同一时间构建两个dict,所以我可以正常地创建我的dicts,只需调用通用的 reverseict
功能到底。
但是,似乎 bidict reverseict 函数似乎是他的双手的〜
运算符)。
Given a one-to-one dictionary (=bijection) generated à la
for key, value in someGenerator:
myDict[key] = value
an inverse lookup dictionary can be trivially created by adding
invDict[value] = key
to the for
loop. But is this a Pythonic way? Should I instead write a class Bijection(dict)
which manages this inverted dictionary in addition and provides a second lookup function? Or does such a structure (or a similar one) already exist?
What I've done in the past is created a reversedict
function, which would take a dict and return the opposite mapping, either values to keys if I knew it was one-to-one (throwing exceptions on seeing the same value twice), or values to lists of keys if it wasn't. That way, instead of having to construct two dicts at the same time each time I wanted the inverse look-up, I could create my dicts as normal and just call the generic reversedict
function at the end.
However, it seems that the bidict solution that Jon mentioned in the comments is probably the better one. (My reversedict
function seems to be his bidict's ~
operator).
这篇关于有没有更好的方式存储一个双语字典比存储其反向分离?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!