我正在尝试做一些看起来非常简单的事情,并且属于标准 python 的范围。以下函数接受集合的集合,并返回两个或多个集合中包含的所有项目。
为此,虽然集合的集合不为空,但它只是从集合中弹出一个集合,将其与其余集合相交,并更新落在这些交集之一中的一组项目。
def cross_intersections(sets):
in_two = set()
sets_copy = copy(sets)
while sets_copy:
comp = sets_copy.pop()
for each in sets_copy:
new = comp & each
print new, # Print statements to show that these references exist
print in_two
in_two |= new #This is where the error occurs in IronPython
return in_two
上面是我正在使用的功能。为了测试它,在 CPython 中,可以执行以下操作:
>>> a = set([1,2,3,4])
>>> b = set([3,4,5,6])
>>> c = set([2,4,6,8])
>>> cross = cross_intersections([a,b,c])
set([2, 4]) set([])
set([4, 6]) set([2, 4])
set([3, 4]) set([2, 4, 6])
>>> cross
set([2, 3, 4, 6])
但是,当我尝试使用 IronPython 时:
>>> b = cross_intersections([a,b,c])
set([2, 4]) set([])
set([4, 6]) set([2, 4])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:/path/to/code.py", line 10, in cross_intersections
SystemError: Object reference not set to an instance of an object.
在标题中我说过这是一个神秘的空指针异常。我可能不知道 .NET 如何处理空指针(我从未使用过类似 C 的语言,并且只使用 IronPython 一个月左右),但如果我的理解是正确的,当您尝试访问指向的对象的某些属性null
.
在本例中,错误发生在我的函数的第 10 行:in_two |= new
。不过,我已经把print
在这一行之前的陈述(至少对我来说)表明这些对象都没有指向null
.
我哪里错了?