4

案子:

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

这是一种简单的方法吗?

最好的问候克里斯

4

2 回答 2

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)]
于 2013-07-02T17:54:14.597 回答
0

这是用于删除重复项的简单 Python3 示例。另一位贡献者涵盖了其他两个。

ixs = {tup[0]:i for i, tup in list(enumerate(a))[::-1]}
[a[i] for i in sorted(ixs.values())]
于 2013-07-02T18:16:03.457 回答