[英]Matching the keys of a dictionary with a reference list and getting the values
我正在处理字典的问题并且遇到了障碍,所以我有一个 3D 列表,其中包含用于参考的坐标和一个字典,其键与列表中的坐标匹配,我需要的是,如果键和然后,坐标匹配 append 另一个 3D 列表中的值。 我几乎知道该怎么做,但我没有得到我想要的,这就是我尝试过的:
reference = [[[2, 3], [2, 4], [3, 2], [4, 2]],
[[2, 3], [3, 2], [3, 4], [4, 3]],
[[2, 3], [3, 2], [3, 4], [4, 3]]]
mydict = {(2, 3): [5, 1], (2, 4): [14, 16], (3, 2): [19, 1], (3, 4): [14, 30], (4, 2): [16, 9], (4, 3): [6, 2]}
aux = [[tuple(j) for j in i] for i in reference] #This transform the 3D list to tuples to match the keys
print(aux)
aux = [[(2, 3), (2, 4), (3, 2), (4, 2)], [(2, 3), (3, 2), (3, 4), (4, 3)], [(2, 3), (3, 2), (3, 4), (4, 3)]]
aux_list = []
for key, value in mydict.items():
final_list =[]
for i in aux:
for j in i: #If the key matches the list of tuples then append the value
if j == key:
aux_list.append(value)
final_list.append(aux_list)
print(final_list)
final_list = [[[5, 1], [5, 1], [5, 1], [14, 16], [19, 1], [19, 1], [19, 1], [14, 30], [14, 30], [16, 9], [6, 2], [6, 2]]]
这给了我正确的值,但是它的顺序有点混乱,虽然它是 3D 列表,但它不像参考列表,这应该是我想要的 output:
final_list = [[[5, 1], [14, 16], [19, 1], [16, 9]],
[[5, 1], [19, 1], [14, 30], [6, 2]],
[[5, 1], [19, 1], [14, 30], [6, 2]]]
这只是一个例子,我相信绝对应该有一个简单的方法来做到这一点,但我有点新手,所以我不确定问题到底是什么,所以任何帮助或参考将不胜感激,非常感谢!
reference = [[[2, 3], [2, 4], [3, 2], [4, 2]],
[[2, 3], [3, 2], [3, 4], [4, 3]],
[[2, 3], [3, 2], [3, 4], [4, 3]]]
mydict = {(2, 3): [5, 1], (2, 4): [14, 16], (3, 2): [19, 1], (3, 4): [14, 30], (4, 2): [16, 9], (4, 3): [6, 2]}
out = [[mydict.get(tuple(v), v) for v in row] for row in reference]
from pprint import pprint
pprint(out)
印刷:
[[[5, 1], [14, 16], [19, 1], [16, 9]],
[[5, 1], [19, 1], [14, 30], [6, 2]],
[[5, 1], [19, 1], [14, 30], [6, 2]]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.