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

Python如何匹配列表中元组的后6位元素并返回对应首元素

实现方案

下面给出两种适配不同使用场景的实现方式:

方法1:单次查询直接遍历

如果只是偶尔查询一次,直接遍历列表做匹配即可,代码逻辑简单无额外开销:

num = [(1,4,5,30,33,41,52),(2,10,11,29,30,36,47),(3,15,25,37,38,58,59)]

def match_tuple(target: tuple, num_list: list) -> int | None:
    for item in num_list:
        # 取元组最后6位和目标组合匹配
        if item[1:] == target:
            return item[0]
    # 无匹配结果返回None
    return None

# 示例测试
target_test = (10,11,29,30,36,47)
print(match_tuple(target_test, num)) # 输出结果为2

注意:如果你的输入目标组合是列表格式,调用前用tuple(目标列表)转成元组即可匹配。

方法2:多次查询预建映射字典

如果需要频繁做匹配查询,提前构建映射字典可以把单次查询的时间复杂度降到O(1),效率更高:

num = [(1,4,5,30,33,41,52),(2,10,11,29,30,36,47),(3,15,25,37,38,58,59)]

# 预构建「最后6位: 首元素」的映射字典
match_map = {item[1:]: item[0] for item in num}

def match_tuple_fast(target: tuple, match_map: dict) -> int | None:
    return match_map.get(target)

# 示例测试
target_test = (10,11,29,30,36,47)
print(match_tuple_fast(target_test, match_map)) # 输出结果为2

无匹配结果时两种方法默认返回None,可以根据业务需要自行调整默认返回值或者加异常捕获逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 23:06:08