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

Python如何合并二维列表中对应相同整数的元组内部列表(禁用字典)

实现元组合并的方案

实现思路:先将原列表按元组的第一个整数值排序,让相同键值的元素连续排列,再遍历排序后的列表,合并相邻同键值的内部列表即可。

def merge_tuples(input_list):
    if not input_list:
        return []
    # 按元组第一个元素排序
    sorted_list = sorted(input_list, key=lambda x: x[0])
    result = []
    current_key, current_val = sorted_list[0][0], sorted_list[0][1].copy()
    for item in sorted_list[1:]:
        key, val = item
        if key == current_key:
            current_val.extend(val)
        else:
            result.append((current_key, current_val))
            current_key = key
            current_val = val.copy()
    # 加入最后一组数据
    result.append((current_key, current_val))
    return result

# 测试验证
list1 = [(0, [1]), (1, [0]), (1, [3]), (1, [9]), (2, [1]), (2, [4]), (3, [5]), (8, [1])]
output = merge_tuples(list1)
print(output)

运行输出结果:[(0, [1]), (1, [0, 3, 9]), (2, [1, 4]), (3, [5]), (8, [1])]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 22:54:04