只是好奇,有没有更好的方法从一个循环中的对象列表中提取属性列表?
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, [[], [], []])
答案 0 :(得分:0)
如果你想在一个循环中完成它,只需删除reduce并循环执行:
xs, ys, zs = [], [], []
for point in points:
xs.append(point.x)
ys.append(point.y)
zs.append(point.z)
使用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)]