Reputation: 77
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]
Obj1.myList = [O1, O2, O3]
Obj2.myList = [O4, O5, O6]
Obj3.myList = [O7, O8, O9]
I need this:
L = [O1, O2, O3, O4, ...., O9];
I tried extend()
and reduce()
but didn't work
bigList = reduce(lambda acc, slice: acc.extend(slice.coresetPoints.points), self.stack, [])
P.S.
Looking for python flatten a list of list didn't help as I got a list of lists of other object.
Upvotes: 2
Views: 7123
Reputation: 140186
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?)
Upvotes: 6
Reputation: 149823
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]
Upvotes: 0
Reputation: 19806
You can achieve that with one-line list comprehension
:
[i for obj in List1 for i in obj.myList]
Upvotes: 4
Reputation: 95672
Not exactly rocket science:
L = []
for obj in List1:
L.extend(obj.myList)
Upvotes: -3