remove matching pairs

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Evan

    #1

    remove matching pairs

    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

  • Tim Chase

    #2
    Re: remove matching pairs

    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...somethin g
    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(pai r)
    #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





    Comment

    • Evan

      #3
      Re: remove matching pairs

      That's great, thank you, the caveats are no matter!

      -Evan

      Comment

      Working...