Are Python operations (intersection, union, duplication) possible with nested lists / tuples?

Happening:

  a = [(1,2), (2,3), (4,5), (1,6), (1,7)]
 b = [(5.2), (6.3), (4.5), (6.8), (1.9)] 

How to remove duplicates using the first element of a tuple?

The result for a will be:

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

Result for b:

  [(5.2), (6.3), (4.5), (1.9)] 

How can I combine both without duplicates ?: The result will be:

  [(1,2), (2,3), (4,5), (5,2), (6,3)] 

How can I get the intersection of both? The result will be:

  [(1,2), (4,5)] 

Is this easy to do?

Best regards chris

+4
source share
2 answers

Use sets:

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

Union:

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

Intersections:

 >>> 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
source

Here is a simple Python3 example for removing duplicates. Another contributor reviewed the other two.

 ixs = {tup[0]:i for i, tup in list(enumerate(a))[::-1]} [a[i] for i in sorted(ixs.values())] 
0
source

Source: https://habr.com/ru/post/1489331/


All Articles