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

如何处理元组列表中的重复自值与对称元组并保留唯一项?

元组列表处理需求

需要对给定元组列表完成以下处理:

  • 移除所有重复的自值元组(如(2, 2)、(0, 0))
  • 对称元组仅保留其一:(2, 1)与(1, 2)留一个,(1, 0)与(0, 1)留一个
  • 去除重复的(0, 2)元组

待处理元组列表:

[(0, 2), (2, 2), (2, 1), (1, 2), (2, 2), (0,2),  (2, 2), (2, 1), (1, 0), (0, 0), (0, 1)]

生成该列表的代码

from itertools import pairwise, chain

lis = [(0, [75, 1, 30]), (1, [41, 49, 55]), (2, [28, 53, 45])]

found = [*chain(*(pairwise(a) for *a, a[1:] in lis))]

print(found)
处理方案

可以通过过滤+标识去重的方式实现需求,具体逻辑:

  1. 先跳过所有自值元组(两个元素相等的元组)
  2. 用排序后的元组作为对称元组的统一标识,通过集合记录已处理过的标识,只保留首次出现的元组

实现代码:

original_list = [(0, 2), (2, 2), (2, 1), (1, 2), (2, 2), (0,2),  (2, 2), (2, 1), (1, 0), (0, 0), (0, 1)]

processed_result = []
seen_symbols = set()

for tpl in original_list:
    # 跳过自值元组
    if tpl[0] == tpl[1]:
        continue
    # 生成排序后的元组作为对称元组的统一标识
    sorted_tpl = tuple(sorted(tpl))
    if sorted_tpl not in seen_symbols:
        seen_symbols.add(sorted_tpl)
        processed_result.append(tpl)

print(processed_result)

执行结果:

[(0, 2), (2, 1), (1, 0)]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 08:56:08