简体   繁体   English

如何在列表理解中实现嵌套循环

[英]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 其中凌晨2点是开始,凌晨5点是结束,约翰是用户名

You can leverage python builtin getattr along with nested list comprehension to achieve what you are envisaging. 您可以利用python内置的getattr和嵌套列表推导来实现您的预​​期。

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 值得注意的是,您的理解力是笛卡尔乘积,而不是嵌套的理解力

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM