我可以使用推导式来比较这些字典列表吗?

0 投票
1 回答
33 浏览
提问于 2025-04-14 17:50

标题就是这样。我正在努力理解这个问题。现在我在基本代码上添加复杂功能时遇到了困难。我觉得用一种更简洁的方式来处理这个问题会更简单,但我找不到可以参考的例子,所以如果能给我一些启发就太好了。

范围:

  1. 尝试通过字典中的“network”值来匹配列表元素。如果在new_routes中找不到与old_routes元素匹配的项,就应该打印一个警告。
  2. 如果在两个列表中找到了“network”值的匹配,就比较这两个字典的“nexthop_ip”,并打印出new_route的nexthop_ip是改变了还是保持不变。
  3. 我可能还需要对其他值进行第2步的比较。

提前谢谢你。

old_routes = [
    {
        "network": "10.11.11.11",
        "distance": "20",
        "metric": "0",
        "nexthop_ip": "10.155.155.155",
    },
    {
        "network": "10.22.22.22",
        "distance": "20",
        "metric": "0",
        "nexthop_ip": "10.99.99.99",
    },
    {
        "network": "10.33.33.33",
        "distance": "20",
        "metric": "0",
        "nexthop_ip": "10.66.66.66",
    }
]
new_routes = [
    {
        "network": "10.11.11.11",
        "distance": "20",
        "metric": "0",
        "nexthop_ip": "10.155.155.155",
    },
    {
        "network": "10.22.22.22",
        "distance": "20",
        "metric": "0",
        "nexthop_ip": "10.77.77.77",
    }
]

for old_route in old_routes:
    for new_route in new_routes:
        if old_route["network"] == new_route["network"]:
            if old_route["nexthop_ip"] == new_route["nexthop_ip"]:
                print(f"{new_route['network']} has no routing changes.")
            else:
                print(f"{new_route['network']} has changed nexthop IPs from {old_route['nexthop_ip']} to {new_route['nexthop_ip']}")

1 个回答

0
old_networks = set(route["network"] for route in old_routes)
new_networks = set(route["network"] for route in new_routes)

for network in old_networks - new_networks:
    print(f"Warning: {network} not found in new_routes")

for new_route in new_routes:
    try:
        old_route = next(route for route in old_routes if route["network"] == new_route["network"])
        if old_route["nexthop_ip"] == new_route["nexthop_ip"]:
            print(f"{new_route['network']} has no routing changes.")
        else:
            print(f"{new_route['network']} has changed nexthop IPs from {old_route['nexthop_ip']} to {new_route['nexthop_ip']}")
    except StopIteration:
        print(f"Warning: {new_route['network']} not found in old_routes")

第一部分处理的是那些在 new_routes 中缺失的路由,第二部分则处理需求 #2(比较IP地址,然后是下一跳)。

撰写回答