2016-05-10 5 views
1

Ich habe eine Liste von Objekten: obj_list unten wie:Wie bekomme ich eine flache Liste von einer verschachtelten Liste mit Verständnis?

obj_1 = SomeObj() 
obj_2 = SomeObj() 
obj_1.items = [obj10, obj11, obj12] 
obj_2.items = [obj20, obj21, obj22] 
obj_list = [obj_1, obj_2] 

Jetzt möchte ich eine Liste, die alle Elemente enthält, wie unten Verständnis mit:

[obj10, obj11, obj12, obj20, obj21, obj22] 

ich versucht habe, wie folgt:

[item for item in obj.items for obj in obj_list] 

Antwort

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

Danke. Ich brauchte dieses [[Objekt für Obj in obj_list für Element in obj.items]]. –

Verwandte Themen