我有一个对象列表:obj_list
如下所示:
obj_1 = SomeObj()
obj_2 = SomeObj()
obj_1.items = [obj10, obj11, obj12]
obj_2.items = [obj20, obj21, obj22]
obj_list = [obj_1, obj_2]
现在我需要一个包含所有项目的列表,使用理解:
[obj10, obj11, obj12, obj20, obj21, obj22]
我尝试过如下:
[item for item in obj.items for obj in obj_list]
答案 0 :(得分:0)
>>> class SomeObj:
... pass
...
>>> obj1=SomeObj()
>>> obj1.items=[1, 2, 3]
>>> obj2=SomeObj()
>>> obj2.items=[4, 5, 6]
>>> obj_list=[obj1, obj2]
>>> [obj.items for obj in obj_list]
[[1, 2, 3], [4, 5, 6]]
>>> [item for obj in obj_list for item in obj.items]
[1, 2, 3, 4, 5, 6]
>>> import itertools
>>> list(itertools.chain(*[obj.items for obj in obj_list]))
[1, 2, 3, 4, 5, 6]