问题
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.
回答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]
回答2:
You can achieve that with one-line list comprehension:
[i for obj in List1 for i in obj.myList]
回答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]
回答4:
Not exactly rocket science:
L = []
for obj in List1:
L.extend(obj.myList)
来源:https://stackoverflow.com/questions/41521431/python-flatten-a-list-of-objects