Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expanding tuples in list comprehension generator

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

like image 803
user3214546 Avatar asked May 30 '15 22:05

user3214546


2 Answers

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] 
like image 128
Bhargav Rao Avatar answered Sep 18 '22 23:09

Bhargav Rao


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.

like image 42
Padraic Cunningham Avatar answered Sep 20 '22 23:09

Padraic Cunningham