简体   繁体   中英

Subtract two lists of tuples from each other

I have the these two lists and I need to subtract one from the other but the regular "-" won't work, neither will .intersection or XOR (^).

A = [(0, 1)]
B = [(0, 0), (0,1), (0, 2)]

Essentially what I want is:

B - A = [(0, 0), (0, 2)]

You can use list comprehension to solve this problem:

[item for item in B if item not in A]

More discussion can be found here

If there are no duplicate tuples in B and A , might be better to keep them as sets, and use the difference of sets:

A = [(0, 1)]
B = [(0, 0), (0,1), (0, 2)]
diff = set(B) - set(A) # or set(B).difference(A)
print(diff)
# {(0, 0), (0, 2)}

You could perform other operations like find the intersection between both sets:

>>> set(B) & set(A)
{(0, 1)}

Or even take their symmetric_difference :

>>> set(B) ^ set(A)
{(0, 0), (0, 2)}

You can do such operations by converting the lists to sets. Set difference:

r = set(B)-set(A)

Convert to list if necessary: list(r)

Working on sets is efficient compared to running "in" operations on lists: using lists vs sets for list differences

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