1

for types such as list I can readily create an empty list to make this construct work:

 s = []
 s+= [1,2,3]  # result s assigned [1,2,3]

obviously useful in constructs like this:

 s=[]
 for v in (list1,list2,list3..):
   if condition : s+=v

Now I'm working with a user defined type, defined in a module that I cannot read or change.. I have to do this:

 s=0
 for v in (typefoo1,typefoo2,..):
   if condition :
    if s==0 :
     s=v
    else:
     s+=v

This works, but is ugly and occurs so often it is pretty annoying. so.. is there a way to create an empty object such that the += operator would behave simply like a regular assignment= regardless of the type on the r.h.s?

Edit: I tried to keep the question generic deliberately, but for completeness the type in question is an Abaqus geometry sequence.

4

2 回答 2

2

有没有办法创建一个空对象,使得+=运算符的行为就像一个常规赋值=,而不管 rhs 上的类型如何?

当然。只需编写一个类并定义您的__add__方法以返回未修改的 RHS。

class DummyItem:
    def __add__(self, other):
        return other

s = DummyItem()
s += 23
print s

结果:

23
于 2015-06-11T14:21:36.223 回答
1

假设您的列表至少有一个元素,您可以创建一个迭代器并使用它next来获取第一个元素,然后将其余元素相加:

i = iter(lst)
s = next(i)
for x in i:
    s += x

您也可以使用该sum函数执行此操作,第二个参数指定初始值:s = sum(i, next(i))。这明确地不适用于 strings,但您也可以reduce以类似的方式使用,这适用于 strings: s = reduce(operator.add, i, next(i))。或者,您甚至可以将其与DummyItem@Kevin的答案结合起来,如s = sum(lst, DummyItem()). 这样它也适用于字符串,您可以直接使用列表而无需创建迭代器。

于 2015-06-11T14:34:08.060 回答