Python – 将矩阵转换为坐标字典
有时,在使用Python字典时,我们可能会遇到需要将矩阵元素转换为其坐标列表的问题。这类问题可能出现在许多领域,包括日间编程和竞争性编程。让我们讨论可以执行此任务的某些方式。
Input : test_list = [[‘g’, ‘g’, ‘g’], [‘g’, ‘g’, ‘g’]]
Output : {‘g’: {(0, 1), (1, 2), (0, 0), (1, 1), (1, 0), (0, 2)}}
Input : test_list = [[‘a’, ‘b’, ‘c’]]
Output : {‘a’: {(0, 0)}, ‘b’: {(0, 1)}, ‘c’: {(0, 2)}}
方法 #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))
The original list is : [[‘g’, ‘f’, ‘g’], [‘i’, ‘s’, ‘g’], [‘b’, ‘e’, ‘s’, ‘t’]]
The Coordinate Dictionary : {‘g’: {(1, 2), (0, 0), (0, 2)}, ‘f’: {(0, 1)}, ‘t’: {(2, 3)}, ‘i’: {(1, 0)}, ‘b’: {(2, 0)}, ‘e’: {(2, 1)}, ‘s’: {(1, 1), (2, 2)}}
方法 #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))
The original list is : [[‘g’, ‘f’, ‘g’], [‘i’, ‘s’, ‘g’], [‘b’, ‘e’, ‘s’, ‘t’]]
The Coordinate Dictionary : {‘g’: {(1, 2), (0, 0), (0, 2)}, ‘f’: {(0, 1)}, ‘t’: {(2, 3)}, ‘i’: {(1, 0)}, ‘b’: {(2, 0)}, ‘e’: {(2, 1)}, ‘s’: {(1, 1), (2, 2)}}