Reputation: 21
I defined two variables list and tuple which I am trying to find the intersection of. In the one case things work as I expected, but in the 2nd the intersection fails and I would have expected it to pass. Can someone point out the obvious for me?
Bob
# Test results in 'Match' as expected
a = ['*']
b = ('*', 'APR', 'Line')
if list(set(a) & set(b)):
print ('Match')
# Test result DOES NOT result in 'Match' whcih was not expected
a = ['APR, SIGEVENT']
b = ('*', 'APR', 'Line')
if list(set(a) & set(b)):
print ('Match')
Upvotes: 0
Views: 2774
Reputation: 1121486
Your second example cannot match, because 'APR, SIGEVENT'
is one string. Python won't split that string and check for string contents for you.
Set intersections require equality between the elements, containment is not one of the options. In other words, since 'APR' == 'APR, SIGEVENT'
is not true, there is no intersection between the two sets, even though 'APR' in 'APR, SIGEVENT'
is true.
You'd have to split out a
into separate strings:
a = ['APR, SIGEVENT']
b = ('*', 'APR', 'Line')
if set(el.strip() for substr in a for el in substr.split(',')).intersection(b):
# intersection between text in a and elements in b
This assumes that you really wanted to test for elements in the comma-separated string(s) in a
here.
Note that for your intersection tests, it is rather overkill to cast the resulting intersection set back to a list.
Demo:
>>> a = ['APR, SIGEVENT']
>>> b = ('*', 'APR', 'Line')
>>> set(el.strip() for substr in a for el in substr.split(',')).intersection(b)
set(['APR'])
Upvotes: 4