[英]Extract list of attributes from list of objects in python
I have an uniform list of objects in python: 我在python中有一个统一的对象列表:
class myClass(object):
def __init__(self, attr):
self.attr = attr
self.other = None
objs = [myClass (i) for i in range(10)]
Now I want to extract a list with some attribute of that class (let's say attr), in order to pass it so some function (for plotting that data for example) 现在我想提取一个列表,其中包含该类的某些属性(让我们说attr),以便将其传递给某些函数(例如用于绘制该数据)
What is the pythonic way of doing it, 什么是pythonic方式,
attr=[o.attr for o in objsm]
? ?
Maybe derive list and add a method to it, so I can use some idiom like 也许派生列表并添加一个方法,所以我可以使用一些成语
objs.getattribute("attr")
? ?
attrs = [o.attr for o in objs]
was the right code for making a list like the one you describe. attrs = [o.attr for o in objs]
是制作类似你所描述的列表的正确代码。 Don't try to subclass list
for this. 不要尝试为此子类化list
。 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 . 有关更多优势,请参阅Generator Expressions 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.