Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how can I refer to a return-value from a function called within a generator expression?

Simplified, I want to do something like this:

({'publication': obj.pub_name, 'views': obj.views, } for obj = analyze_publication(p) for p in Publication.objects.all())

Of course, that doesn't work.

Right now, I'm using:

({'publication': obj.pub_name, 'views': obj.views, } for obj in (analyze_publication(p) for p in Publication.objects.all()))

I have no idea if the second code piece is how it's done or there's another syntax, or it's not efficient etc. I'm only 2 weeks into Python.

like image 566
ForeverLearnNeverMaster Avatar asked May 26 '26 05:05

ForeverLearnNeverMaster


1 Answers

Just another version:

( dict(publication= obj.pub_name, views= obj.views) 
    for obj in map(analyze_publication, Publication.objects.all()) )
like image 139
warvariuc Avatar answered May 27 '26 20:05

warvariuc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!