Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract list of attributes from list of objects in python

Tags:

python

loops

list

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

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)

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

?

like image 928
franjesus Avatar asked Apr 29 '10 18:04

franjesus


People also ask

How do you find the attributes of an object in Python?

getattr() – This function is used to access the attribute of object. hasattr() – This function is used to check if an attribute exist or not. setattr() – This function is used to set an attribute. If the attribute does not exist, then it would be created.

How do you sort a list of objects by attribute in Python?

A simple solution is to use the list. sort() function to sort a collection of objects (using some attribute) in Python. This function sorts the list in-place and produces a stable sort. It accepts two optional keyword-only arguments: key and reverse.


1 Answers

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?

like image 56
Mike Graham Avatar answered Oct 02 '22 07:10

Mike Graham