首页 > 解决方案 > 如何在python中创建两个组元素之间的映射?

问题描述

考虑我有两组字符串元素(不必要的字符串 - 仅用于示例):“strA1,strA2,strA3”和“strB1,strB2,strB3”。我想根据已知的法律将第一个列表中的元素与第二个列表中的元素映射成唯一的对,我可以在第一个列表中逐个元素地找到第二个列表中的元素,反之亦然。
我知道三种方法来做到这一点。

方法一:创建地图

{'strA1':'strB1', 'strA2':'strB2', 'strA3':'strB3'}

在这种情况下,我可以通过键从第二个列表中找到一个元素。但是如果我想从第一个列表中找到元素,我必须遍历所有字典键。

方法2:创建两个地图:

{'strA1':'strB1', 'strA2':'strB2', 'strA3':'strB3'}

{'strB1':'strA1', 'strB2':'strA2', 'strB3':'strA3'}

在这种情况下,我可以在两个列表中按键找到一个元素,但我必须为此保留两个地图。

方法 3: 创建有意义的索引(手动或使用枚举)并使用特殊参数从元组中的对中选择一个元素:

from enum import Enum
Index = Enum('Index', ['PAIR_A1B1', 'PAIR_A2B2', 'PAIR_A3B3'], start=0)  #understandable names
 #direction
A2B = 0
B2A = 1   
mappingList = [('strA1','strB1'), ('strA2','strB2'), ('strA3','strB3')]
print(mappingList[Index.PAIR_A1B1.value][A2B]) # I get my mapped string here

还有其他方法吗?

标签: pythonpython-3.xmapping

解决方案


您也可以尝试使用bidict库:

from bidict import bidict

group1=["strA1", "strA2", "strA3"]   
group2=["strB1", "strB2", "strB3"]
    
dc=dict(zip(group1,group2))   #we create the dictionary by using zip to create the tuples and then cast it to a dict
    
newdc= bidict(dc)             #we create the bi-directional dictionary

print(newdc['strA1'])
print(newdc.inverse['strB1'])

输出:

strB1
strA1

推荐阅读