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

在二维列表中确认指定值存在后,如何获取对应关联元素?

获取二维列表中指定元素的关联值

已知二维列表:

list_data = [[123, 'Fred'],[234234, 'Martha'],[89182038,'Adam']]

(注:避免用list作为变量名,它是Python内置类型)

已经通过any(123 in sublist for sublist in list_data)确认123存在于某个子列表中,以下是几种获取对应关联元素'Fred'的方法:

  • 遍历查找法
    直接遍历列表,找到包含目标值的子列表后,取其第二个元素(索引为1):

    target_num = 123
    for sublist in list_data:
        if target_num in sublist:
            associated_name = sublist[1]
            print(associated_name)  # 输出 Fred
            break
    
  • 生成器表达式快速提取
    用生成器表达式直接筛选出目标子列表,再取对应元素,适合一行代码实现:

    target_num = 123
    associated_name = next(sublist[1] for sublist in list_data if target_num in sublist)
    print(associated_name)  # 输出 Fred
    

    因为已经确认目标值存在,所以用next()不会抛出StopIteration异常。

  • 字典映射法
    如果需要多次通过数字查找对应名称,可以先把二维列表转换成字典,后续查询更高效:

    name_map = {num: name for num, name in list_data}
    target_num = 123
    associated_name = name_map[target_num]
    print(associated_name)  # 输出 Fred
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:35:35