3 回答

TA貢獻1951條經驗 獲得超3個贊
要比較兩個列表的交集,使用sets會很有幫助,尤其是當您的列表有兩個以上的元素時。
a = ['m', 'n']
b = ['n', 'o']
print(set(a) & set(b)) # The & operator returns the intersecting elements
-> {'n'}
至于你的問題,這段代碼應該有效:
for a in A:
B = A.copy()
B.remove(a) # so you don't compare a to a and mark it as a duplicate
for b in B:
if set(b[0]) & set(b[1]):
A.remove(b)

TA貢獻1876條經驗 獲得超6個贊
要比較兩個列表的交集,使用sets會很有幫助,尤其是當您的列表有兩個以上的元素時。
a = ['m', 'n']
b = ['n', 'o']
print(set(a) & set(b)) # The & operator returns the intersecting elements
-> {'n'}
至于你的問題,這段代碼應該有效:
for a in A:
B = A.copy()
B.remove(a) # so you don't compare a to a and mark it as a duplicate
for b in B:
if set(b[0]) & set(b[1]):
A.remove(b)

TA貢獻1811條經驗 獲得超5個贊
試試這個:
>>> import numpy as np
>>> def remove_duplicates(A):
... for sublist in A:
... sublist.sort()
... B = []
... for sublist in A:
... if sublist not in B:
... B.append(sublist)
... return B
...
>>> A = np.random.randint(low=0, high=3, size=(8, 2)).tolist()
>>> A
[[0, 1], [1, 0], [0, 2], [0, 0], [2, 2], [2, 2], [0, 2], [1, 0]]
>>> remove_duplicates(A)
[[0, 1], [0, 2], [0, 0], [2, 2]]
在 python 3.7.7 上測試。
添加回答
舉報