Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create list of object attributes in python

Tags:

python

I have a list of objects:

[Object_1, Object_2, Object_3]

Each object has an attribute: time:

Object_1.time = 20
Object_2.time = 30
Object_3.time = 40

I want to create a list of the time attributes:

[20, 30, 40]

What is the most efficient way to get this output? It can't be to iterate over the object list, right?:

items = []
for item in objects:
    items.append(item.time)
like image 331
Ed. Avatar asked Jun 19 '12 01:06

Ed.


2 Answers

List comprehension is what you're after:

list_of_objects = [Object_1, Object_2, Object_3]
[x.time for x in list_of_objects]
like image 127
mhawke Avatar answered Oct 05 '22 03:10

mhawke


from operator import attrgetter
items = map(attrgetter('time'), objects)
like image 44
John La Rooy Avatar answered Oct 05 '22 05:10

John La Rooy