【问题标题】:How to get unique combinations of pairs in nested tuples?如何在嵌套元组中获得唯一的对组合?
【发布时间】:2026-01-14 19:45:01
【问题描述】:

我有一个 [(tuple1), (tuple2)] 形式的对列表,其中第一个元组的长度可变,第二个长度为 1。

例子:

[((0, 1, 2), 0), 
((3, 4, 5), 0), 
((12,), 1), 
((0, 1, 4, 7), 1), 
((12,), 1),
((3, 4, 5), 0)]

我想要set(pairs),其中tuple1_pair_X = tuple1_pair_Y && tuple2_pair_X = tuple2_pair_Y,而不是tuple1 元素与tuple2 的所有可能组合。

期望的输出:

[((0, 1, 2), 0), 
((3, 4, 5), 0), 
((12,), 1), 
((0, 1, 4, 7), 1)] 

【问题讨论】:

  • 你能提供一个你尝试过的实现,它可以帮助我们改进你的答案
  • 我只尝试了set()命令,输出为[(0, ), 0, (1, ), 0, (2, ), 0 , ...] 等非- 重复元素

标签: python list tuples list-comprehension


【解决方案1】:

如果您想保持列表的顺序:

lst = [((0, 1, 2), 0), 
((3, 4, 5), 0), 
((12,), 1), 
((0, 1, 4, 7), 1), 
((12,), 1),
((3, 4, 5), 0)]

sorted(set(lst), key=lst.index)

输出:

[((0, 1, 2), 0), 
((3, 4, 5), 0), 
((12,), 1), 
((0, 1, 4, 7), 1)] 

【讨论】:

    【解决方案2】:

    我想简单地在原始元组列表上使用 set() 命令应该可以工作并给出您想要的输出。

    tup_list = [((0, 1, 2), 0), ((3, 4, 5), 0),((12,), 1),((0, 1, 4, 7), 1),((12,), 1),((3, 4, 5), 0)]
    output = list(set(tup_list))
    

    【讨论】: