qwe ewq qwe ewq - 1 month ago 8
Python Question

Extract listS of attributes from list of objects in python

Just curious, is there a nicer way to extract lists of attributes from an list of objects in one loop?

def _f(acc, p):
acc[0].append(p.x)
acc[1].append(p.y)
acc[2].append(p.z)
return acc

xs, ys, zs = reduce(_f, points, [[], [], []])

Answer

If you want to do it in one loop, just drop the reduce and do it in a loop:

xs, ys, zs = [], [], []
for point in points:
    xs.append(point.x)
    ys.append(point.y)
    zs.append(point.z)

It can be done more succinctly with zip:

>>> points = [types.SimpleNamespace(x=it, y=it+1, z=it*2+1) for it in range(3)]
>>> points
[namespace(x=0, y=1, z=1), namespace(x=1, y=2, z=3), namespace(x=2, y=3, z=5)]
>>> list(zip(*((point.x, point.y, point.z) for point in points)))
[(0, 1, 2), (1, 2, 3), (1, 3, 5)]
Comments