简体   繁体   中英

remove pairs of equal elements from two lists in sympy

I am quite new to Sympy (running with Python 3).
Given two lists of integers, in general not of equal lengths and whose elements might repeat, I need to eliminate all pairs of equal elements between the two lists. For example, given
List_a=[1, 2, 3, 4, 4], List_b=[0, 2, 2, 4]
I shall eliminate the pairs (2,2) and (4,4) and output
List_ar=[1,3,4], List_br=[0,2]
If the two lists are equal I shall get two empty lists as output.
I have been trying to compare the lists element by element ( "for" and "while" loops) and when found equal to delete the pair from both lists. Upon that to repeat the procedure on the reduced lists till no deletion is made. But lacking of a "goto" control I do not know how to handle the variable length lists.
Thanks for helping.

I you convert them to multiset you can compare the counts of common keys:

>>> from sympy.utilities.iterables import multiset
>>> ma = multiset(lista)
>>> mb = multiset(listb)
>>> for k in set(ma) & set(mb):
...    n = min(ma[k],mb[k])
...    ma[k] -= n
...    mb[k] -= n
...
>>> lista = [i for k in ma for i in [k]*ma[k]]
>>> listb = [i for k in mb for i in [k]*mb[k]]

You could also treat this like a merge sort but the above is direct.

A general Python solution:

def g(a, b):
    def ensure2(xs):
        ys = [list(x) for x in xs]

        if ys == []:
            return [[], []]
        else:
            return ys

    n = min(len(a), len(b))

    c, d = ensure2(
            zip(*
                filter(lambda x: x[0] != x[1], 
                zip(a, b))))

    return c + a[n:], d + b[n:]

a = [1,2,3,4,4]
b = [0,2,2,4]
c = [0,2,2,4]
d = []

# two different lists
ar, br = g(a, b)
print(ar)  # [1, 3, 4]
print(br)  # [0, 2]

# two identical lists
br, cr = g(b, c)
print(br)  # []
print(cr)  # []

# one empty list
ar, dr = g(a, d)
print(ar)  # [1, 2, 3, 4, 4]
print(dr)  # []
  • Use zip() to create the pairs
  • Use filter() to remove pairs with equal elements
  • Use zip(*...) to split the remaining pairs back to two lists
  • Use ensure2() to guard against empty lists
  • Use + list[n:] to append excessive elements back to the originally longer list

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM