简体   繁体   中英

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]

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, [])

PS

Looking for python flatten a list of list didn't help as I got a list of lists of other object.

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? )

您可以通过单行list comprehension来实现:

[i for obj in List1 for i in obj.myList]

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]

Not exactly rocket science:

L = []
for obj in List1:
    L.extend(obj.myList)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM