Python: Flatten A List Of Objects
I have a list of Objects and each object has inside it a list of other object type. I want to extract those lists and create a new list of the other object. List1:[Obj1, Obj2, Obj3
Solution 1:
using itertools.chain
(or even better in that case itertools.chain.from_iterable
as niemmi noted) which avoids creating temporary lists and using extend
import itertools
print(list(itertools.chain(*(x.myList for x in List1))))
or (much clearer and slightly faster):
print(list(itertools.chain.from_iterable(x.myList for x in List1)))
small reproduceable test:
class O:
def __init__(self):
pass
Obj1,Obj2,Obj3 = [O() for _ in range(3)]
List1 = [Obj1, Obj2, Obj3]
Obj1.myList = [1, 2, 3]
Obj2.myList = [4, 5, 6]
Obj3.myList = [7, 8, 9]
import itertools
print(list(itertools.chain.from_iterable(x.myList for x in List1)))
result:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
(all recipes to flatten a list of lists: How to make a flat list out of list of lists?)
Solution 2:
You can achieve that with one-line list comprehension
:
[i for obj in List1 for i in obj.myList]
Solution 3:
list.extend()
returns None
, not a list. You need to use concatenation in your lambda function, so that the result of the function call is a list:
bigList = reduce(lambda x, y: x + y.myList, List1, [])
While this is doable with reduce()
, using a list comprehension would be both faster and more pythonic:
bigList = [x for obj in List1 for x in obj.myList]
Solution 4:
Not exactly rocket science:
L = []
for obj in List1:
L.extend(obj.myList)
Post a Comment for "Python: Flatten A List Of Objects"