python - 如何在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
还有其他方法吗?
解决方案
您也可以尝试使用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
推荐阅读
- testing - CYPRESS - 如何获取用户的令牌以访问同一 Cypress 窗口中的其他选项卡,放置 cy.visist(URL + TOKEN)
- tensorflow - 如何在训练相同的 Keras 模型时打印模型每一层的激活?
- jquery - 代码在函数内部时不运行
- javascript - ElectronJS ReferenceError:未定义导航器
- python - Pandas - 选择其他列行满足两个条件的索引
- assembly - 程序集 x86 中的分段错误
- python - 如何定义具有动态属性的类?
- android - 录制音频时 Firebase 模拟器测试失败
- date - Google 表格中的多年服务公式
- angular - 如何配置我的角度库以使用正确安装的 RxJS 链接它进行本地测试?