简体   繁体   English

在python中创建对象属性列表

[英]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: 每个对象都有一个属性: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)

List comprehension is what you're after: 列表理解是你所追求的:

list_of_objects = [Object_1, Object_2, Object_3]
[x.time for x in list_of_objects]

怎么样:

items=[item.time for item in objects]
from operator import attrgetter
items = map(attrgetter('time'), objects)

The fastest (and easiest to understand) is with a list comprehension. 最快(最容易理解)是列表理解。

See the timing: 看时间:

import timeit
import random
c=10000

class SomeObj:
    def __init__(self, i):
        self.attr=i

def loopCR():
    l=[]
    for i in range(c):
        l.append(SomeObj(random.random()))

    return l 

def compCR():
    return [SomeObj(random.random()) for i in range(c)]   

def loopAc():
    lAttr=[]
    for e in l:
        lAttr.append(e.attr)

    return lAttr

def compAc():
    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 is 18.3364670069 % faster

loop access: 0.0206878185272 secs
comprehension access: 0.00913000106812 secs
Faster of those is 55.8677438315 % faster

So list comprehension is both faster to write and faster to execute. 因此,列表理解的写入速度更快,执行速度更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM