class - Summing Attribute in a list of Python Objects -
similar "what's concise way in python group , sum list of objects same property", have script in need sum attributes of list of objects. however, issue differs slightly.
i have class of objects attributes v, w, x, y, , z. need sum attribute z iterating through , matching attributes w, x, , y other w, x, , y attributes same. producing new summed value indexed w, x, , y.
here class objects:
class xb(object): def __init__(self, v, w, x, y, z): self.v = v self.w = w self.x = x self.y = y self.z = z xbs = [xb()]
my initial thought through series of nested if statements slows processing considerably , i'm sure logic out of whack.
for xb in xbs: if xb.w == xb.w: if xb.x == xb.x: if xb.y == xb.y: sum(xb.z)
any suggestions on appreciated!
you can using defaultdict:
from collections import defaultdict indexed_sums = defaultdict(int) o in xbs: indexed_sums[(o.w, o.x, o.y)] += o.z
for instance, if start (using class definition of xb
):
xbs = [xb(1, 2, 3, 4, 5), xb(1, 2, 3, 4, 5), xb(1, 2, 3, 4, 5), xb(1, 4, 3, 4, 5), xb(1, 4, 3, 4, 3), xb(1, 2, 3, 9, 3)]
you end with:
print dict(indexed_sums) # {(4, 3, 4): 8, (2, 3, 4): 15, (2, 3, 9): 3}
thus, sum w, x, y being 2, 3, 4 as:
indexed_sums[(2, 3, 4)] # 15
note defaultdict
doing little work here (it's dictionary of counts starts @ 0 default): main thing indexing (o.w, o.x, o.y)
tuples in dictionary. have done same thing without defaultdict
as:
indexed_sums = {} o in xbs: if (o.w, o.x, o.y) not in indexed_sums: indexed_sums[(o.w, o.x, o.y)] = 0 indexed_sums[(o.w, o.x, o.y)] += o.z
the defaultdict
saving 2 lines.
Comments
Post a Comment