簡體   English   中英

比較python3中列表元組中的元素的問題

[英]issue with comparing elements within tuples of a list in python3

我試圖比較列表的元組中的元素,並僅提取不常見的值,但由於某種原因,它返回整個組合。 例如,如果我傳遞這樣的值:

[(3,2), (2,4)]

然后它應該返回

[(3,4)]

這是我嘗試的:

a=[]
for i in range(len(l)):
    j=i+1
    for j in range(len(l)):
        print(i)
        print(j)
        if l[i][0]==l[j][0]:
            a.append((l[i][1],l[j][1]))
            print(a)
        elif l[i][0]==l[j][1]:
            a.append((l[i][1],l[j][0]))
            print(a)
        elif l[i][1]==l[j][0]:    
            a.append((l[i][0],l[j][1]))
            print(a)
        elif l[i][1]==l[j][1]:
            a.append((l[i][0],l[j][0]))
            print(a)

我試圖構建一個更通用的代碼來處理不同種類的輸入,但是它不能處理所有情況。 它為[[3,2),(2,4)]的單個比較提供了兩種可能性。它給出3 4和4 3均為輸出。

Sample inputs tried
>>onehop([(2,3),(1,2)]) input 
>>[(1, 3)] expected output
>>onehop([(2,3),(1,2),(3,1),(1,3),(3,2),(2,4),(4,1)]) input
>>[(1, 2), (1, 3), (1, 4), (2, 1), (3, 2), (3, 4), (4, 2), (4, 3)] output
>>onehop([(1,2),(3,4),(5,6)]) input
>>[] expected output
>>onehop([(1,2),(2,1)]) input
>>[ ] expected output
>>onehop([(1,2)]) input
>>[ ] expected output
>>onehop([(1,3),(1,2),(2,3),(2,1),(3,2),(3,1)]) input
>>[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)] expected output

是否有更優化的代碼或可能的列表理解。 我對此並不陌生,正在學習這是我嘗試過的方法。

def onehop(l):
    a = []
    b = []
    c = []
    for i in range(len(l)):
        j = i+1
        for j in range(len(l)):
            print(i) 'Just to understand the loops'
            print(j)
            if l[i][0] == l[j][1] and l[i][1] != l[j][0]:
                a.append((l[i][1],l[j][0]))
            elif l[i][0] != l[j][1] and l[i][1] == l[j][0]:
                a.append((l[i][0],l[j][1]))
            elif l[i][0] == l[j][0] and l[i][1] != l[j][1]:
                a.append((l[i][1],l[j][1]))
            elif l[i][0] != l[j][0] and l[i][1] == l[j][1]:
                a.append((l[i][0],l[j][0]))
    b = list(set(a))
    b.sort()
    return b

看起來像是一個疏忽,但是您設置了j並立即用for -loop覆蓋了它,這說明了獲得所有組合的原因:它還將每個元素與其自身進行比較。

如果插入手動計算的j作為下限,則似乎適用於您的情況:

l = [(3,2),(2,4)]
a = []
for i in range(len(l)):
    for j in range(i+1, len(l)):  # changed!
        if l[i][0]==l[j][0]:
            a.append((l[i][1],l[j][1]))
        elif l[i][0]==l[j][1]:
            a.append((l[i][1],l[j][0]))
        elif l[i][1]==l[j][0]:    
            a.append((l[i][0],l[j][1]))
        elif l[i][1]==l[j][1]:
            a.append((l[i][0],l[j][0]))
print(a)
# [(3, 4)]

可能您可以使用@Bill Bell指出的set操作來簡化代碼(並使其更快):

例如, tuple(set((3,2)).symmetric_difference(set((2,4))))得出(3, 4)

def remove_dup(L):
    if L == ():
        return ()
    else:
        return L[0] + remove_dup(tuple(map(lambda li: tuple(filter(lambda x: x not in L[0], li)), L[1:])))

print(remove_dup([(3,2),(2,4)]))
-->
(3, 2, 4)

print(remove_dup([(3,2,9),(2,4),(4,3,8,9),(9,7),(8,)]))
-->
(3, 2, 9, 4, 8, 7)

暫無
暫無

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

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