I have two sets of tuples a
and b
.
a = set([(1,'a'),(34,'b'), (82,'c')])
b = set([(8,'a'),(98,'c')])
I want a set c
such that
c = set([(34,'b')])
What is the most efficient way of doing this operation in python ?
I guess O(n) is the most efficient:
>>> b2 = {x for n,x in b}
>>> c = {(n,x) for (n,x) in a if x not in b2}
>>> c
{(34, 'b')}
I would start by using dicts instead of sets for a and b:
a = {k: v for (v, k) in a}
b = {k: v for (v, k) in b}
Then, it is just a matter of taking the content of a
that is not in b
print [(k, a[k]) for k in set(a.keys()) - set(b.keys())]
or
b_keys = set(b.keys())
print [(k,v) for (k,v) in a.items() if k not in b_keys}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.