从 python 中的对象列表中提取属性列表

我有一个 Python 中对象的 制服列表:

class myClass(object):
def __init__(self, attr):
self.attr = attr
self.other = None


objs = [myClass (i) for i in range(10)]

现在我想提取一个包含该类的某个属性的列表(比方说 attr) ,以便向它传递某个函数(例如绘制该数据)

蟒蛇式的做法是什么,

attr=[o.attr for o in objsm]

也许派生列表并向其添加一个方法,这样我就可以使用一些习惯用法,如

objs.getattribute("attr")

115918 次浏览

attrs = [o.attr for o in objs] was the right code for making a list like the one you describe. Don't try to subclass list for this. Is there something you did not like about that snippet?

You can also write:

attr=(o.attr for o in objsm)

This way you get a generator that conserves memory. For more benefits look at Generator Expressions.