我正在尝试做一些看似非常简单的事情,并且属于标准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
。
我哪里错了?
答案 0 :(得分:3)
It's a bug。它将在2.7.1中修复,但我不认为修复版本在2.7.1 Beta 1版本中。
答案 1 :(得分:1)
这是2.7.1 Beta 1版本中仍然存在的bug。
已修复master,修复程序将包含在下一版本中。
IronPython 3.0 (3.0.0.0) on .NET 4.0.30319.235
Type "help", "copyright", "credits" or "license" for more information.
>>> import copy
>>>
>>> def cross_intersections(sets):
... in_two = set()
... sets_copy = 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
...
>>>
>>> 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])