Create List Of Object Attributes In 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 t
Solution 1:
List comprehension is what you're after:
list_of_objects = [Object_1, Object_2, Object_3]
[x.time for x in list_of_objects]
Solution 2:
from operator import attrgetter
items = map(attrgetter('time'), objects)
Solution 3:
The fastest (and easiest to understand) is with a list comprehension.
See the timing:
import timeit
import random
c=10000classSomeObj:
def__init__(self, i):
self.attr=i
defloopCR():
l=[]
for i inrange(c):
l.append(SomeObj(random.random()))
return l
defcompCR():
return [SomeObj(random.random()) for i inrange(c)]
defloopAc():
lAttr=[]
for e in l:
lAttr.append(e.attr)
return lAttr
defcompAc():
return [e.attr for e in l]
t1=timeit.Timer(loopCR).timeit(10)
t2=timeit.Timer(compCR).timeit(10)
print"loop create:", t1,"secs"print"comprehension create:", t2,"secs"print'Faster of those is', 100.0*abs(t1-t2) / max(t1,t2), '% faster'print
l=compCR()
t1=timeit.Timer(loopAc).timeit(10)
t2=timeit.Timer(compAc).timeit(10)
print"loop access:", t1,"secs"print"comprehension access:", t2,"secs"print'Faster of those is', 100.0*abs(t1-t2) / max(t1,t2), '% faster'
Prints:
loop create: 0.103852987289 secs
comprehension create: 0.0848100185394 secs
Faster of those is18.3364670069 % faster
loop access: 0.0206878185272 secs
comprehension access: 0.00913000106812 secs
Faster of those is55.8677438315 % faster
So list comprehension is both faster to write and faster to execute.
Post a Comment for "Create List Of Object Attributes In Python"