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

Python

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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)

Solution 2 - Python

are you looking for something like this?

[o.specific_attr for o in objects]

Solution 3 - Python

The first thing that came to my mind:

attrList = map(lambda x: x.attr, objectList)

Solution 4 - Python

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

[o.b for o in objects]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJanis VeinbergsView Question on Stackoverflow
Solution 1 - PythonJarret HardieView Answer on Stackoverflow
Solution 2 - PythonSilentGhostView Answer on Stackoverflow
Solution 3 - PythonCoffee on MarsView Answer on Stackoverflow
Solution 4 - PythonRossFabricantView Answer on Stackoverflow