I am using this function
def convert_tuple(self, listobj, fields=['start', 'end', 'user']):
return [(getattr(obj, field) for field in fields)
for obj in listobj]
My desired output which I want should be
[('2am', '5am', 'john'), ('3am', '5am', 'john1'), ('3am', '5am', 'john2') ]
The output of above function is
[genexp, genexp, genexp]
Its generator expression and I was not able to expand it like I wanted
Typecast the gen-exp to a tuple
def convert_tuple(self, listobj, fields=['start', 'end', 'user']):
return [tuple(getattr(obj, field) for field in fields)
for obj in listobj]
The parens are creating a generator expression call tuple as per Bhargav's answer or you can use operator.attrgetter
with map:
from operator import attrgetter
def convert_tuple(listobj, fields=['start', 'end', 'user']):
return list(map(attrgetter(*fields), listobj)) # python2 just map
Demo:
class Foo():
def __init__(self):
self.x = 1
self.y = 2
self.z = 3
f = Foo()
f2 = Foo()
f2.x = 10
print(convert_tuple([f,f2]))
[(1, 2, 3), (10, 2, 3)]
You can remove the list call for python2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With