我有两个列表(这些记录将长达数百条),但这是示例:
eax
我想从list2取出每个OUI,其中VLAN在两个列表之间匹配,然后将其添加到list1中OUI项的值。 (我想这可能需要第三个命令来容纳所有内容)。
最终结果将类似于:
list1 = [
{'VENDOR': 'VENDOR1', 'VLAN': '500', 'OUI': []},
{'VENDOR': 'VENDOR2', 'VLAN': '600', 'OUI': []},
{'VENDOR': 'VENDOR3', 'VLAN': '700', 'OUI': []},
]
list2 = [
{'VLAN': '500', 'OUI': '0001FC'},
{'VLAN': '600', 'OUI': '00D024'},
{'VLAN': '500', 'OUI': '00D024'},
{'VLAN': '700', 'OUI': '00D024'},
{'VLAN': '700', 'OUI': '023456'},
]
我什至不知道从哪里开始,所以我们将不胜感激。
答案 0 :(得分:1)
这是一种实现方法,关于
(我想这可能需要第三个命令来容纳所有内容)
那不是必须的
list1 = [
{'VENDOR': 'VENDOR1', 'VLAN': '500', 'OUI': []},
{'VENDOR': 'VENDOR2', 'VLAN': '600', 'OUI': []},
{'VENDOR': 'VENDOR3', 'VLAN': '700', 'OUI': []},
]
list2 = [
{'VLAN': '500', 'OUI': '0001FC'},
{'VLAN': '600', 'OUI': '00D024'},
{'VLAN': '500', 'OUI': '00D024'},
{'VLAN': '700', 'OUI': '00D024'},
{'VLAN': '700', 'OUI': '023456'},
]
# to hold indexes of VLAN in list1 so it will be easy to
# append to the right "OUI" list inside list1
indexes = {}
# get the index of each VLAN
for i in range(len(list1)):
indexes[list1[i]["VLAN"]] = i
# `indexes` now => {"500": 0, "600": 1, "700": 2}
for a in list2:
# now it's easy to target the right `"OUI"` list
# for example the first iteration
# list1[0]["OUI"].append("0001FC")
list1[indexes[a["VLAN"]]]["OUI"].append(a["OUI"])
print(list1)
输出:
[
{'VENDOR': 'VENDOR1', 'VLAN': '500', 'OUI': ['0001FC', '00D024']},
{'VENDOR': 'VENDOR2', 'VLAN': '600', 'OUI': ['00D024']},
{'VENDOR': 'VENDOR3', 'VLAN': '700', 'OUI': ['00D024', '023456']}
]
答案 1 :(得分:0)
执行该操作所需的代码在这里:
for i in range(0,len(list1)):
for j in range(0,len(list2)):
if(list1[i]["VLAN"] == list2[j]["VLAN"]):
list1[i]["OUI"].append(list2[j]["OUI"])
并使用以下代码测试是否有正确的输出:
for i in range(0,len(list1)):
print(list1[i]["OUI"])
我相信这段代码是不言自明的,但是如果您想解释为什么会这样,请随时询问。
答案 2 :(得分:0)
我将list1
重组为嵌套字典,其中VLAN
为键,然后迭代list2
并将VLAN
项目添加到OUI
嵌套字典中的列表。然后我们可以只打印嵌套字典的values()
。
list1 = [
{"VENDOR": "VENDOR1", "VLAN": "500", "OUI": []},
{"VENDOR": "VENDOR2", "VLAN": "600", "OUI": []},
{"VENDOR": "VENDOR3", "VLAN": "700", "OUI": []},
]
list2 = [
{"VLAN": "500", "OUI": "0001FC"},
{"VLAN": "600", "OUI": "00D024"},
{"VLAN": "500", "OUI": "00D024"},
{"VLAN": "700", "OUI": "00D024"},
{"VLAN": "700", "OUI": "023456"},
]
vendors = {v["VLAN"]: v for v in list1}
# {'500': {'VENDOR': 'VENDOR1', 'VLAN': '500', 'OUI': []}, '600': {'VENDOR': 'VENDOR2', 'VLAN': '600', 'OUI': []}, '700': {'VENDOR': 'VENDOR3', 'VLAN': '700', 'OUI': []}}
for vlan in list2:
vendors[vlan["VLAN"]]["OUI"].append(vlan["OUI"])
print(list(vendors.values()))
输出:
[{'VENDOR': 'VENDOR1', 'VLAN': '500', 'OUI': ['0001FC', '00D024']}, {'VENDOR': 'VENDOR2', 'VLAN': '600', 'OUI': ['00D024']}, {'VENDOR': 'VENDOR3', 'VLAN': '700', 'OUI': ['00D024', '023456']}]