简体   繁体   English

Python-设置交集无法按预期工作

[英]Python - Set intersection not working as expected

I defined two variables list and tuple which I am trying to find the intersection of. 我定义了两个变量list和元组,它们试图找到它们的交集。 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')

Your second example cannot match, because 'APR, SIGEVENT' is one string. 您的第二个示例无法匹配,因为'APR, SIGEVENT'一个字符串。 Python won't split that string and check for string contents for you. Python不会拆分该字符串并为您检查字符串内容。

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. 换句话说,由于'APR' == 'APR, SIGEVENT'不为真,因此即使'APR' in 'APR, SIGEVENT' 'APR' in 'APR, SIGEVENT'两组之间也没有交集。

You'd have to split out a into separate strings: 你必须打出a为单独的字符串:

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. 这是假设你真的想考在逗号分隔的字符串(S)的元素a在这里。

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'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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