[英]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.