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

Python中如何定义函数搜索列表组成的列表?

嘿,针对你这个嵌套列表的搜索需求,得先看你具体的搜索场景——是按ID精准查找?按姓名匹配?还是按过期日期筛选范围?下面给你分场景讲几种实用方案,从简单到高效都覆盖到:

1. 基础线性搜索(适合小数据集、偶尔搜索)

如果你的数据量不大,或者只是偶尔搜一次,直接遍历整个列表就够了,简单直观不需要额外预处理。比如按ID搜索的示例:

def search_by_id(people_list, target_id):
    for person in people_list:
        # 子列表第一个元素是ID
        if person[0] == target_id:
            return person
    return None  # 没找到匹配项时返回None

要是需要返回所有匹配的(比如你的数据里有两个ID为10207的条目),就改成收集结果:

def search_all_by_id(people_list, target_id):
    matches = []
    for person in people_list:
        if person[0] == target_id:
            matches.append(person)
    return matches

这种方法的缺点是数据量大时效率低,每次搜索都要遍历全列表,时间复杂度是O(n)。

2. 预构建索引字典(适合频繁搜索、大数据集)

如果需要多次执行搜索操作,提前把数据按常用字段做成索引字典是最佳选择,能把搜索时间降到O(1)(单条匹配)或者O(k)(k是匹配条数)。

按ID构建索引(处理重复ID)

考虑到你的数据里有重复ID的情况,把索引值设为列表来存储所有匹配项:

# 提前构建ID到人员列表的索引
id_index = {}
for person in people:
    pid = person[0]
    if pid not in id_index:
        id_index[pid] = []
    id_index[pid].append(person)

# 后续搜索直接查字典,一秒出结果
target_matches = id_index.get('10207', [])  # 没找到返回空列表

按姓氏/名字构建索引

如果经常按姓名搜索,同样可以建对应索引:

# 按姓氏构建索引
last_name_index = {}
for person in people:
    last_name = person[2]
    if last_name not in last_name_index:
        last_name_index[last_name] = []
    last_name_index[last_name].append(person)

# 搜索所有姓Smith的人
smith_folks = last_name_index.get('Smith', [])
3. 日期范围筛选

如果需要按过期日期筛选(比如找某段时间内过期的人),建议先把字符串日期转成datetime对象,方便做范围比较:

from datetime import datetime

def search_by_date_range(people_list, start_str, end_str):
    # 把输入的日期字符串转成datetime对象
    start_date = datetime.strptime(start_str, '%Y-%m-%d')
    end_date = datetime.strptime(end_str, '%Y-%m-%d')
    
    matches = []
    for person in people_list:
        expiry = datetime.strptime(person[1], '%Y-%m-%d')
        if start_date <= expiry <= end_date:
            matches.append(person)
    return matches

# 示例:找2018年5月1日到5月10日过期的人
may_expiries = search_by_date_range(people, '2018-05-01', '2018-05-10')

要是频繁做日期搜索,可以提前把所有日期转成datetime存在索引里,避免每次转换的开销。

4. 多条件组合搜索

如果需要同时满足多个条件(比如ID是10207且姓氏是Smith),可以写一个通用的过滤函数:

def search_with_multi_filters(people_list, filters):
    # 映射字段名到子列表的索引位置
    field_map = {
        'id': 0,
        'expiry': 1,
        'last_name': 2,
        'first_name': 3
    }
    matches = []
    for person in people_list:
        # 检查所有过滤条件是否都满足
        is_match = True
        for field, value in filters.items():
            if person[field_map[field]] != value:
                is_match = False
                break
        if is_match:
            matches.append(person)
    return matches

# 示例:找ID=10207且姓氏=Smith的人
target_people = search_with_multi_filters(people, {'id': '10207', 'last_name': 'Smith'})

总结一下

  • 小数据集/偶尔搜索:用线性搜索,简单省心
  • 频繁搜索/大数据集:优先构建对应字段的索引字典,效率拉满
  • 日期/多条件搜索:写自定义过滤函数,或者结合索引+过滤进一步优化

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:46:22