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

Python算法课作业:在嵌套列表database中查找元素并获取索引

Python嵌套列表元素查找及索引获取方案

要实现查找指定元素并返回其所属子列表在database中的索引,核心是用enumerate()遍历列表,同时获取索引和子列表内容,检查目标元素是否存在于子列表中即可。

方案1:获取所有匹配的索引(支持多个子列表包含同一元素)

# 初始化数据库(保留你原有的输入添加逻辑,也可直接初始化测试数据)
database = []
name = input('type the name: ')
desc = input('type the description: ')
database.append([name, desc])
name = input('type another name: ')
desc = input('type another description: ')
database.append([name, desc])

def find_all_matching_indices(target):
    matching_indices = []
    # enumerate同时返回索引和对应子列表
    for idx, item in enumerate(database):
        if target in item:
            matching_indices.append(idx)
    return matching_indices

# 执行查找操作
target = input("输入要查找的元素: ")
result_indices = find_all_matching_indices(target)

if result_indices:
    print(f"元素 '{target}' 所在的子列表索引为: {result_indices}")
else:
    print(f"未找到元素 '{target}'")

方案2:仅获取第一个匹配的索引

如果只需要第一个出现目标元素的子列表索引,找到后直接返回即可:

def find_first_matching_index(target):
    for idx, item in enumerate(database):
        if target in item:
            return idx
    # 未找到时返回-1作为标识
    return -1

target = input("输入要查找的元素: ")
index = find_first_matching_index(target)
if index != -1:
    print(f"元素 '{target}' 首次出现在索引 {index} 的子列表中")
else:
    print(f"未找到元素 '{target}'")

关键说明

  • enumerate(database)会返回(索引值, 子列表)的元组,让你在遍历过程中直接获取当前子列表在database中的位置,解决了你之前只能判断存在性、拿不到索引的问题。
  • 两种方案分别对应"多个子列表匹配"和"仅需第一个匹配"的场景,可根据作业需求选择使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 11:11:08