我正在处理字典问题,遇到障碍,所以我有一个3D列表,其中包含我用作参考的坐标,还有一个字典,其键与列表中的坐标匹配,这是我需要的,如果键和坐标匹配,然后将值附加到另一个3D列表中。我几乎知道该怎么做,但是我没有得到想要的东西,这是我尝试过的:
localhost/AmazonPay/Client.php
这给了我正确的值,但是顺序有点混乱,尽管它是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]]]
这只是一个例子,我相信绝对应该有一个简单的方法来做到这一点,但是我是一个新手,所以我不确定问题出在哪里,因此任何帮助或参考都将不胜感激,谢谢你好厉害!
答案 0 :(得分: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]]]