我有一类具有整数多项式i,j和k的函数,还有一个浮点系数c和一些无关的输入变量,例如
G(i,j,k,c,a,A)
我有这些对象的列表,并且想要通过添加它们的c来合并i,j和k相同的对象,例如,我要减少
[G(0, 0, 1, 2.0, a, A), G(0, 1, 0, 4.0, a, A), G(0, 0, 1, 1.0, a, A)]
到
[G(0, 0, 1, 3.0, a, A), G(0, 1, 0, 4.0, a, A)]
是否存在接受的pythonic /高效方法?我还找不到任何有人这样做的例子,但似乎经常会出现这种情况。
编辑: 为了清楚起见,下面是实际的类定义。
class PrimitiveGaussian:
#Primitive Gaussian of arbitrary Cartesian exponents
#See Helgaker p. 336 for index conventions
def __init__(self, i = 0, j = 0, k = 0, a = 1.0, A = np.array([0.0,0.0,0.0]), coefficient = 1.0):
self.i = i
self.j = j
self.k = k
self.a = a
self.A = A
self.coefficient = coefficient
答案 0 :(得分:1)
您可以在列表的排序版本上使用itertools.groupby
并指定前三个项目作为键:
test = [(0, 0, 1, 2.0, 'a', 'A'), (0, 1, 0, 4.0, 'a', 'A'), (0, 0, 1, 1.0, 'a', 'A')]
from functools import reduce
import itertools as it
result = [reduce(lambda x, y: (*x[:3], x[3]+y[3], *x[4:]), g)
for k, g in it.groupby(sorted(test), key=lambda x: x[:3])]