简体   繁体   中英

Improving execution speed using nested list comprehension

Below is my code which is taking a long time to execute. How can I implement it in a list comprehension in Python to improve speed and efficiency?

buildings=[]
for bi in range(1449):
    for si in range (16):
        for m in range(3):
            a= train[(train['building_id']==bi)&(train['site_id']==si)&(train['meter']==m)]
            if not a.empty:

                buildings.append(a.values)

Hard to tell if this is correct without your sample data, but this should work theoretically:

buildings = [
             x for x in
                 [
                 train[(train['building_id']==bi)&(train['site_id']==si)&(train['meter']==m)].values
                 for bi in range(1449)
                 for si in range(16)
                 for m in range(3)
                 ]
            if not x.empty
            ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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