简体   繁体   中英

How to create a list with list comprehension and generators

i'm retrieving some data from the active directory with pyad library. Once i execute a query, I would like to create a dataframe with the data retrieved:

import pyad
import pyad.adquery as query

pyad.set_defaults(ldap_server=xxxxxx)
q = query.ADQuery()
q.execute(
    attributes=[attribute1,attribute2,attribute3]
    where_clause=xxx
    base_dn=xxxxx
)

Once i run the query, i'm creating a dataframe in this way:

parameter1 = []
parameter2 = []
parameter3 = []

for x in q.get_results(): #IT'S A GENERATOR
    parameter1.append(x['attribute1'])
    parameter2.append(x['attribute2'])
    parameter3.append(x['attribute3'])

df = pd.Dataframe({'P1':parameter1, 'P2':parameter2, 'P3':parameter3})

The way i'm creating the dataframe is not clean and elegant, is there a way to improve this code? If it would be just one parameter i would do:

df = pd.Dataframe({'P1': [x['parameter1'] for x in q.get_results()]})

but q is a generator so i can't run three list comprehensions without running again the method q.execute(...)

Get the generator out of the way

results = list(q.get_results())

Then you should be able to:

df = pd.Dataframe({'P1': [x['parameter1'] for x in results], 'P2': [x['parameter2'] for x in results], ...})

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