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 上测试。
添加回答
举报