2016-05-10 69 views
1

我有對象的列表: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
>>> 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] 
+0

謝謝。我需要這個'[obj_list中obj_items項目的obj項目]''。 –