remove matching pairs

E

Evan

Is there a simple way to to identify and remove matching pairs from 2
lists?

For example:

I have

a=[2, 5, 3, 4, 7, 2, 2, 4, 8, 1]
b=[7, 3, 5, 8, 1, 7, 4, 8, 2, 6]

and I want to get this:

a=[2, 5, 3, 4, 7, 2, 8, 1]
b=[7, 3, 5, 8, 1, 4, 2, 6]

There are recurring pairs of (2, 7) and (4, 8), and so I want to remove
one of each pair.

Many thanks, Evan
 
T

Tim Chase

Is there a simple way to to identify and remove matching pairs from 2
lists?

For example:

I have

a=[2, 5, 3, 4, 7, 2, 2, 4, 8, 1]
b=[7, 3, 5, 8, 1, 7, 4, 8, 2, 6]

and I want to get this:

a=[2, 5, 3, 4, 7, 2, 8, 1]
b=[7, 3, 5, 8, 1, 4, 2, 6]

Well, with a few caveats, the following works:
>>> a=[2, 5, 3, 4, 7, 2, 2, 4, 8, 1]
>>> b=[7, 3, 5, 8, 1, 7, 4, 8, 2, 6]
>>> a_prime, b_prime = zip(*set(zip(a,b)))
>>> a_prime (2, 8, 4, 7, 1, 5, 2, 3)
>>> b_prime
(7, 2, 8, 1, 6, 3, 4, 5)

Caveat #1: the order changed because sets are unordered
Caveat #2: a_prime and b_prime are tuples, not lists

If this isn't a true solution (because either #1 or #2 is an
unacceptable condition), you'd have to go with a loop...something
like this untested

pairs = zip(a,b)
uniq = set(pairs)
a_prime = []
b_prime = []
for pair in pairs:
if pair in uniq:
a_prime.append(pair[0])
b_prime.append(pair[1])
uniq.remove(pair)
#if not uniq: break

This should preserve the order as well as maintain listsrather
than return tuples. Depending on the number of duplicates you
expect and the size of your a/b lists, uncommenting out that last
line may give you a short speedup, as if you've already pulled
all the items out the uniq set, there's no reason to continue
iterating over the list of pairs.

HTH,

-tkc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top