我有一個“標簽”串列和一個帶有鍵值對“class_dict”的字典。
如果class_dict.value() 等于標簽[i],我想遍歷我的標簽串列,并列印字典鍵(例如'airplane')。
labels = [2, 7, 1, 0, 3, 2, 0, 5, 1, 6, 3, 4, 2, 9, 3, 8]
class_dict ={'airplane': 0, 'automobile': 1, 'bird': 2,'cat': 3,'deer': 4,'dog': 5,'frog': 6, 'horse': 7,'ship': 8,'truck': 9}
例如
labels[0] = 'bird'
labels[1] = 'ship'
labels[2] = 'automobile'
本質上我想這樣做,但以更簡潔的方式:
for i in labels:
for key, val in classes_dict.items():
if val == i:
print(key)
uj5u.com熱心網友回復:
例如,您可以交換 dict 的鍵和值,然后簡單地使用串列元素訪問它:
reversed_dict = {value: key for key, value in class_dict.items()}
new_list = [reversed_dict[x] for x in labels]
print(new_list)
輸出:
['bird', 'horse', 'automobile', 'airplane', 'cat', 'bird', 'airplane', 'dog', 'automobile', 'frog', 'cat', 'deer', 'bird', 'truck', 'cat', 'ship']
uj5u.com熱心網友回復:
請注意您的字典已反轉,因此請先考慮反轉它
labels = [2, 7, 1, 0, 3, 2, 0, 5, 1, 6, 3, 4, 2, 9, 3, 8]
class_dict ={'airplane': 0, 'automobile': 1, 'bird': 2,'cat': 3,'deer': 4,'dog': 5,'frog': 6, 'horse': 7,'ship': 8,'truck': 9}
new_dict = {v: k for k, v in class_dict.items()}
for l in labels:
print(new_dict[l])
uj5u.com熱心網友回復:
假設這些值總是從 0 開始按順序遞增,您只需獲取鍵并進行正常查找
class_keys = class_dict.keys()
labels = [class_keys[i] for i in labels]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/441366.html
上一篇:回圈迭代嵌套字典中的串列
