简体   繁体   中英

How can i implement nested loop in list comprehension

Currently i have this

def convert_tuple(self, listobj, fields=None):
    return [(obj.start, obj.end) for obj in listobj]

But i have hard coded the fields.

I want to have fields as another list like

def convert_tuple(self, listobj, fields=['start', 'end', 'user']):
    return [(obj.field) for obj in listobj for field in fields]

How can i implement that

Expected output

[('2am', '5am', 'john'), ('3am', '5am', 'john1'), ('3am', '5am', 'john2') ]

where 2am is start , 5am is end , john is username

You can leverage python builtin getattr along with nested list comprehension to achieve what you are envisaging.

def convert_tuple(self, listobj, fields=['start', 'end', 'user']):
    return [(getattr(obj, field) for  field in fields)
            for obj in listobj] 

It is worth noting that your comprehension is rather a cartesian product rather than a nested comprehension

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