python - Looking for more pythonic list comparison solution -


ok have 2 lists:

x = [1, 2, 3, 4] y = [1, 1, 2, 5, 6] 

i compare them in such way following output:

x = [3, 4] y = [1, 5, 6] 

the basic idea go through each list , compare them. if have element in common remove element. 1 of element not of them. if don't have element in common leave it. 2 identical lists become x = [], y = []

here rather hacked , pretty lame solution. hoping other can recommend better , / or more pythonic way of doing this. 3 loops seems excessive...

    done = true      while not done:         done = false         x in xlist:             y in ylist:                 if x == y:                     xlist.remove(x)                     ylist.remove(y)                     done = false         print xlist, ylist 

thanks taking time read question. xoxo

it's possible data structure looking multiset (or "bag"), , if so, way implement in python use collections.counter:

>>> collections import counter >>> x = counter([1, 2, 3, 4]) >>> y = counter([1, 1, 2, 5, 6]) >>> x - y counter({3: 1, 4: 1}) >>> y - x counter({1: 1, 5: 1, 6: 1}) 

if want convert counter objects lists multiplicity, can use elements method:

>>> list((x - y).elements()) [3, 4] >>> list((y - x).elements()) [1, 5, 6] 

Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -