案例:
a = [(1,2),(2,3),(4,5),(1,6),(1,7)] b = [(5,2),(6,3),(4,5),(6,8),(1,9)]
如何通过第一个元组项删除重复项?
a的结果将是:
[(1,2),(2,3),(4,5)]
b的结果是:
[(5,2),(6,3),(4,5),(1,9)]
如何在没有重复的情况下合并两者?: 结果将是:
[(1,2),(2,3),(4,5),(5,2),(6,3)]
我怎样才能得到两者的交集?: 结果将是:
[(1,2),(4,5)]
这是否可以轻松实现?
最诚挚的问候 克里斯
答案 0 :(得分:1)
使用套装:
>>> seen = set()
>>> s1 = [x for x in a if x[0] not in seen and not seen.add(x[0])]
>>> seen = set()
>>> s2 = [x for x in b if x[0] not in seen and not seen.add(x[0])]
>>> s1
[(1, 2), (2, 3), (4, 5)]
>>> s2
[(5, 2), (6, 3), (4, 5), (1, 9)]
联:
>>> from itertools import chain
>>> seen = set()
>>> [x for x in chain(s1,s2) if x[0] not in seen and not seen.add(x[0])]
[(1, 2), (2, 3), (4, 5), (5, 2), (6, 3)]
路口:
>>> se1 = set(x[0] for x in s1)
>>> se2 = set(x[0] for x in s2)
>>> inter = se1 & se2
>>> inter
set([1, 4])
>>> seen = set()
>>> [x for x in chain(s1,s2) if x[0] in inter and x[0] not in seen
and not seen.add(x[0])]
[(1, 2), (4, 5)]
答案 1 :(得分:0)
这是删除重复项的简单Python3示例。另一位撰稿人介绍了另外两位。
ixs = {tup[0]:i for i, tup in list(enumerate(a))[::-1]}
[a[i] for i in sorted(ixs.values())]