Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract from a list of objects a list of specific attribute?

Tags:

python

I have a list of objects. Object has 3 string attributes. I want to make a list containing only a specific attribute from class.

Is there any built-in functions to do that?

like image 622
Janis Veinbergs Avatar asked Mar 24 '09 14:03

Janis Veinbergs


People also ask

How do you sort a list of class objects with an 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.

Can you have a list of objects in Python?

We can create list of object in Python by appending class instances to list. By this, every index in the list can point to instance attributes and methods of the class and can access them. If you observe it closely, a list of objects behaves like an array of structures in C.


2 Answers

A list comprehension would work just fine:

[o.my_attr for o in my_list] 

But there is a combination of built-in functions, since you ask :-)

from operator import attrgetter map(attrgetter('my_attr'), my_list) 
like image 164
Jarret Hardie Avatar answered Sep 28 '22 20:09

Jarret Hardie


are you looking for something like this?

[o.specific_attr for o in objects] 
like image 24
SilentGhost Avatar answered Sep 28 '22 22:09

SilentGhost