Fran Martinez
Fran Martinez

Reputation: 679

Getting Set difference in Python 2.7

I have two sets:

set_A = ([('6',90), ('4',315), ('2', 135)])

and

set_B = (['A',90), ('B', 135), ('D', 240)])

I'm looking for a way to get the difference between the two without taking into account the single numbers and the single uppercase letters.

Output expected: ([('4',315)])

Both of these iterations gives me: (['A',90), ('B', 135), ('D', 240)])

different = [item for item in set_B if item not in set_A]

different = set_B.difference(set_A)

I need to keep track of the uppercase letters, and of the single numbers. I don't have any idea of how to do this.

Is there a way to do this?

Upvotes: 0

Views: 76

Answers (3)

vendaTrout
vendaTrout

Reputation: 156

You are almost right, assuming we only need to check duplication on the second element of each tuple, you can simply do :

For Set A - Set B

different = [item for item in set_A if item[1] not in zip(*set_B)[1]]
different
[('4', 315)]

For Set B - Set A

different = [item for item in set_B if item[1] not in zip(*set_A)[1]]
different
[('D', 240)]

Hope this helps!

Upvotes: 1

MSeifert
MSeifert

Reputation: 152667

You could convert them to dictionaries because set.difference on the dictionary keys is really cheap:

>>> # Inverted dictionaries because you want to match the second element
>>> dict_A = {key: value for value, key in set_A}
>>> dict_B = {key: value for value, key in set_B}

>>> [(dict_A[key], key) for key in set(dict_A).difference(dict_B)]
[('4', 315)]

The last step does the difference that you wanted but it also converts it back to a list of tuples.

Upvotes: 1

jeff carey
jeff carey

Reputation: 2373

I think this is what you're after, if not please clarify your reqs:

diff = set(a_item for a_item in set_A if a_item[1] not in [b_item[1] for b_item in set_B])

Upvotes: 2

Related Questions