📜  Python – 将矩阵转换为坐标字典

📅  最后修改于: 2022-05-13 01:55:06.211000             🧑  作者: Mango

Python – 将矩阵转换为坐标字典

有时,在使用Python字典时,我们可能会遇到需要将矩阵元素转换为其坐标列表的问题。这类问题可能出现在许多领域,包括日间编程和竞争性编程。让我们讨论可以执行此任务的某些方式。

方法 #1:使用循环 + enumerate()
上述功能的组合可用于执行此任务。在此,我们使用蛮力提取元素并在 enumerate() 的帮助下为它们分配索引。

# Python3 code to demonstrate working of 
# Convert Matrix to Coordinate Dictionary
# Using loop + enumerate()
  
# initializing list
test_list = [['g', 'f', 'g'], ['i', 's', 'g'], ['b', 'e', 's', 't']]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Convert Matrix to Coordinate Dictionary
# Using loop + enumerate()
res = dict()
for idx, sub in enumerate(test_list):
    for j, ele in enumerate(sub):
        if ele in res:
            res[ele].add((idx, j))
        else:
            res[ele] = {(idx, j)}
  
# printing result 
print("The Coordinate Dictionary : " + str(res)) 
输出 :

方法 #2:使用setdefault() + 循环
此方法的操作方式与上述类似,不同之处在于setdefault()减少了记忆元素值和键存在检查的任务。

# Python3 code to demonstrate working of 
# Convert Matrix to Coordinate Dictionary
# Using setdefault() + loop
  
# initializing list
test_list = [['g', 'f', 'g'], ['i', 's', 'g'], ['b', 'e', 's', 't']]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Convert Matrix to Coordinate Dictionary
# Using setdefault() + loop
res = dict()
for idx, ele in enumerate(test_list):
    for j, sub in enumerate(ele):
        res.setdefault(sub, set()).add((idx, j))
  
# printing result 
print("The Coordinate Dictionary : " + str(res)) 
输出 :