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

Python如何识别并处理元组列表中元素相同顺序不同的重复元组

问题根因
  • 遍历列表过程中删除元素会触发列表索引动态偏移,导致部分元素未被遍历就直接跳过
  • 原有判断逻辑(A,B) == (B,A)仅能匹配两个元素完全相同的元组(如(5,5)),完全无法识别「元素相同、顺序相反」的配对元组
实现方案

通过规范化元组特征的方式完成匹配:将每个元组排序后作为唯一标识,第一次出现的元组保留在uplink,重复出现的(含反向配对)归入downlink:

uplink = [(6, 26), (15, 26), (26, 48), (26, 65), (48, 26), (48, 92), (65, 26), (65, 92), (88, 26), (92, 48), (92, 65)]
downlink = []
seen = set()
new_uplink = []

for item in uplink:
    # 排序生成统一特征,正向、反向元组的特征完全一致
    norm = tuple(sorted(item))
    if norm not in seen:
        seen.add(norm)
        new_uplink.append(item)
    else:
        downlink.append(item)

# 替换原有uplink列表
uplink = new_uplink
运行结果

处理后两个列表的输出为:

  • uplink:[(6, 26), (15, 26), (26, 48), (26, 65), (48, 92), (65, 92), (88, 26)]
  • downlink:[(48, 26), (65, 26), (92, 48), (92, 65)]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 20:54:03