You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何高效替换字典列表中空值为对应匹配的Host与Url值

解决方案

这里提供两种不同场景下的O(n)时间复杂度高效实现,远优于逐元素匹配的O(n²)方案:

场景1:前半部分Host条目与后半部分Url条目顺序严格一一对应

如果你的输入列表确定符合「第i个Host条目对应第i个Url条目」的顺序规则,直接拆分列表对应赋值即可,实现最简单性能最高:

# 输入列表
input_list = [
    {"Host": "dailymotion", "Url": ""},
    {"Host": "youtube", "Url": ""},
    {"Host": "Vimeo", "Url": ""},
    {"Host": "", "Url": "https://www.dailymotion.com/video/x37j4ox"},
    {"Host": "", "Url": "https://www.youtube.com/watch?v=uDLQfA2o0"},
    {"Host": "", "Url": "https://vimeo.com/42399207"}
]

half_len = len(input_list) // 2
result = []
# 遍历对应位置的元素直接赋值
for host_item, url_item in zip(input_list[:half_len], input_list[half_len:]):
    host_item["Url"] = url_item["Url"]
    result.append(host_item)

print(result)

场景2:条目顺序不固定,需要按Host与Url的关联关系匹配

如果列表顺序是乱的,需要通过Url域名和Host的对应关系匹配,用哈希表做中间映射,单次遍历即可完成:

from urllib.parse import urlparse

input_list = [
    {"Host": "dailymotion", "Url": ""},
    {"Host": "youtube", "Url": ""},
    {"Host": "Vimeo", "Url": ""},
    {"Host": "", "Url": "https://www.dailymotion.com/video/x37j4ox"},
    {"Host": "", "Url": "https://www.youtube.com/watch?v=uDLQfA2o0"},
    {"Host": "", "Url": "https://vimeo.com/42399207"}
]

# 第一步:构建Host小写映射表,查找时间O(1)
host_map = {}
for item in input_list:
    if item["Host"]:
        # 用小写做匹配key,保留原始Host的大小写
        host_map[item["Host"].lower()] = item

# 第二步:遍历Url条目匹配赋值
for item in input_list:
    if item["Url"]:
        # 解析Url提取二级域名作为匹配key
        domain = urlparse(item["Url"]).netloc
        match_key = domain.split(".")[-2]
        if match_key in host_map:
            host_map[match_key]["Url"] = item["Url"]

# 输出结果
result = list(host_map.values())
print(result)

两种方案运行后都可以得到你需要的预期输出。

内容的提问来源于stack exchange,提问作者john_fnv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 15:15:02