如何 return 元组列表中的唯一元素作为另一个元组

How to return unique elements in list of tuple as another tuple

假设我有元组列表 a=[(0,1),(2,0),(1,4)] 并且我想 return 每两个元组的唯一元素作为一个新元组。例如 (0,1)(2,0) returns(1,2)。还有 (0,1)(1,4) return (0,4).

因此,输出为unique=[(1,2),(0,4)]

我尝试了下面的代码,但似乎我的路径不正确:

from itertools import combinations
a=[(0,1),(2,0),(1,4)]

b=list(combinations(a,2))
def myComp(pair1, pair2):
    if any(x == y for x, y in zip(pair1, pair2)):
        return(pair1,pair2)

d=[]
for i in range(len(b)):
    c=myComp(b[i][0],b[i][1])
    d.append(c) 

没有任何列表的粗略答案:

from itertools import combinations

a = [(0,1),(0,2),(0,3),(1,2),(1,3),(1,4),(2,3)]

uniques = []
for x, y in combinations(a,2):
    z = []
    for i in x:
        if i not in y:
           z.append(i)
    for i in y:
        if i not in x:
           z.append(i)
    if len(z) == 2:
        uniques.append(tuple(z))

print(list(set(uniques)))
[(0, 1), (2, 4), (1, 2), (0, 4), (3, 4), (0, 3), (2, 3), (0, 2), (1, 3)]

首先,将a中的所有元组转换为集合。

a2 = [set(i) for i in a]

然后,取a2的两个元素的组合。

b2 = itertools.combinations(a2, 2)
# print(list(b2)) gives:
# [({0, 1}, {0, 2}), ({0, 1}, {1, 4}), ({0, 2}, {1, 4})]

然后,对于 b2 中的每一对,找出对称差异。

answer = [tuple(x ^ y) for x, y in b2]
# answer: [(1, 2), (0, 4), (0, 1, 2, 4)]

就像 Ironkey 在评论中提到的那样,您在最后一个元素中得到 (0, 1, 2, 4),因为您正在比较 (0, 2)(1, 4),并且这些元组中的所有元素都是互斥的。

要过滤掉四元素元组,你可以简单地添加那个条件:

answer_f = [x for x in answer if len(x) == 2]
# answer_f: [(1, 2), (0, 4)]

这不使用包。

条件 if i != x and a.index(i)<a.index(x) 确保我们不会比较相同的元组,而且我们只会比较同一对元组一次

然后我们就抓取不在另一个元组中的元素

条件 if len(m) == 2 and sorted(m) in uniq 确保列表只有 2 个元素长,并且还解决了您关于具有 (2,1) & (1,2)

的评论
a=[(0,1),(2,0),(1,4),(0,2)]

uniq = []
for i in a:
  for x in a:
    if i != x and a.index(i)<a.index(x):
      m = [y for y in i if y not in x] + [z for z in x if z not in i]
      if len(m) == 2 and tuple(sorted(m)) not in uniq:
        uniq.append(tuple(m))

print(uniq)

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