qwe ewq qwe ewq - 11 months ago 66
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):
return acc

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

Answer Source

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:

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)]