我有ChromosomeInterval
个对象列表,其中包含方法union
。我想按顺序将此方法应用于列表的每个成员。我希望使用reduce
使用lambda
执行此操作。但是,当我这样做时,我有以下错误:
>>> result
[ChromosomeInterval('1', 0, 0, '+'), ChromosomeInterval('1', 8, 10, '+'), ChromosomeInterval('1', 10, 10, '+')]
>>> reduce(lambda x, y: x.union(y), result)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
AttributeError: 'list' object has no attribute 'union'
但是,如果我将union
更改为+
的经典reduce
运算符用法,我会收到错误,因为ChromosomeInterval
没有__add__
方法:
>>> reduce(lambda x, y: x + y, result)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
TypeError: unsupported operand type(s) for +: 'ChromosomeInterval' and 'ChromosomeInterval'
这两者有什么区别?为什么union
的调用对list
进行调用,而对+
个对象的ChromosomeInterval
运算符调用?