考虑到我有两组字符串元素(不必要的字符串-仅用于示例):
“strA1、strA2、strA3”和“strB1、strB2、strB3”。
我想将第一个列表中的元素与第二个列表中的元素映射成唯一的对,根据已知的规律,我可以在第二个列表中按第一个列表中的元素找到元素,反之亦然。
我知道三种方法
方法1:创建地图
{'strA1':'strB1', 'strA2':'strB2', 'strA3':'strB3'}
在本例中,我可以通过键从第二个列表中找到一个元素。但如果我想从第一个列表中找到元素,我必须遍历所有字典键
方法2:创建两个映射:
{'strA1':'strB1', 'strA2':'strB2', 'strA3':'strB3'}
{'strB1':'strA1', 'strB2':'strA2', 'strB3':'strA3'}
在这种情况下,我可以在两个列表中按键找到一个元素,但我必须为此保留两个映射
方法3:创建有意义的索引(手动或使用enum),并使用特殊参数从元组中的一对中选择一个元素:
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
还有其他方法吗
您也可以尝试使用^{} 库:
输出:
正向和反向映射可能是您的最佳选择。下面是一种通过单个对象(添加了反向字典的dictionary子类)访问它们的方法
显然,它仍然需要分配内存,尽管这两个字典将使用对其中包含的相同对象的引用,而不是重复的对象
给出:
它需要
相关问题 更多 >
编程相关推荐