tags:

views:

122

answers:

4

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?

A: 

Assuming you want field b for the objects in a list named objects do this:

[o.b for o in objects]
RossFabricant
I assume you meant [o.b for o in objects].
unbeknown
+2  A: 

The first thing that came to my mind:

attrList = map(lambda x: x.attr, objectList)
Coffee on Mars
What's wrong with lambda?
Jeremy Cantrell
+6  A: 

are you looking for something like this?

[o.specific_attr for o in objects]
SilentGhost
+9  A: 

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)
Jarret Hardie
Excellent. Thank you!
Janis Veinbergs
that's not a built-in if you need to import. ;) http://docs.python.org/library/functions.html
SilentGhost
I plead nuance: "built-in" != "__builtins__'. Well, that's my story and I'm sticking to it, officer. :-)
Jarret Hardie