从python中的对象列表中提取属性列表 [英] Extract list of attributes from list of objects in python

查看:284
本文介绍了从python中的对象列表中提取属性列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中有一个 uniform 对象列表:

I have an uniform list of objects in python:

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

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

现在我想提取一个具有该类某些属性的列表(比如attr),以便将其传递给某个函数(例如用于绘制数据)

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)

Python的实现方式是什么,

What is the pythonic way of doing it,

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

?

推荐答案

您还可以编写:

attr=(o.attr for o in objsm)

这样,您将获得一个节省内存的生成器.有关更多好处,请参见生成器表达式.

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

这篇关于从python中的对象列表中提取属性列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆