簡體   English   中英

如何將元組列表中的唯一元素作為另一個元組返回

[英]How to return unique elements in list of tuple as another tuple

假設我有元組列表a=[(0,1),(2,0),(1,4)]並且我想將每兩個元組的唯一元素作為新元組返回。 例如(0,1)(2,0)返回(1,2) (0,1)(1,4)也返回(0,4)

因此,output 是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) 

首先,將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)]

沒有任何列表組合的粗略答案:

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)]

這不使用包。

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)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM