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

如何检查JSON地址是否包含邮编列表子串并筛选数据

筛选包含指定邮编的JSON地址条目

问题背景

现有如下格式的JSON地址数据:

{"locations":[
    {"location_id": "1",
     "ref": "123 street apt 5N, New York, 10001, USA"
    },
    {"location_id": "2",
     "ref": "124 street apt 6B, New York, 10002, USA"
    },
    {"location_id": "3",
     "ref": "125 street apt 2A, New York, 10002, USA"
    },
    {"location_id": "4",
     "ref": "303 broad ave, New York, 10005, USA"
    }
  ]
}

邮编列表:

zipcode_list = [10002, 10003, 10004, 10005]

预期筛选出ref字段包含列表中任意邮编的条目,返回结果:

{"locations":[
    {"location_id": "2",
     "ref": "124 street apt 6B, New York, 10002, USA"
    },
    {"location_id": "3",
     "ref": "125 street apt 2A, New York, 10002, USA"
    },
    {"location_id": "4",
     "ref": "303 broad ave, New York, 10005, USA"
    }
  ]
}

错误分析

尝试的代码返回错误 'in ' requires string as left operand, not list,原因有两点:

  • df.values.tolist()返回的是嵌套列表(比如[[10002], [10003]]),遍历zipcode_list时,xs是子列表,无法和字符串x['ref']做in匹配。
  • 邮编是数字类型,而ref是字符串,数字不能直接在字符串中做子串匹配,需要转成字符串。

修正后的代码

步骤1:正确处理邮编列表

先将嵌套列表展平,同时把每个邮编转成字符串,方便后续匹配:

import json
import pandas as pd

# 读取邮编列表并处理成一维字符串列表
df = pd.read_csv('C:/Users/C/Desktop/zipcode_list.csv')
# 展平嵌套列表并转字符串
zipcode_list = [str(item) for sublist in df.values.tolist() for item in sublist]

# 读取JSON数据并筛选
with open('C:/Users/C/Downloads/NY.json', 'r+', errors="ignore") as f:
    data = json.load(f)
    filtered_locations = []
    for loc in data['locations']:
        ref = loc['ref']
        # 检查任意邮编是否在ref中,匹配到就跳出循环减少计算
        for zipcode in zipcode_list:
            if zipcode in ref:
                filtered_locations.append(loc)
                break
    result = {'locations': filtered_locations}

# 格式化输出结果
print(json.dumps(result, indent=2))

大数据量优化说明

  • 使用显式循环搭配break,匹配到邮编后立即停止当前条目的检查,减少不必要的计算。
  • 提前将所有邮编转成字符串,避免循环中重复转换操作。
  • 采用逐条目遍历的方式,避免一次性加载过多数据到内存,适合处理大体积JSON文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 17:15:43