4

我正在尝试做一些看起来非常简单的事情,并且属于标准 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.

我哪里错了?

4

2 回答 2

3

这是一个错误。它将在 2.7.1 中修复,但我不认为修复在 2.7.1 Beta 1 版本中。

于 2011-07-15T20:26:57.217 回答
1

这是2.7.1 Beta 1 版本中仍然存在的错误。

它已在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])
于 2011-07-15T21:46:54.373 回答