Python:展平对象列表 [英] 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]
我需要这个:
L = [O1, O2, O3, O4, ...., O9];
我尝试了extend()
和reduce()
,但是没有用
I tried extend()
and reduce()
but didn't work
bigList = reduce(lambda acc, slice: acc.extend(slice.coresetPoints.points), self.stack, [])
P.S.
寻找python展平列表的列表并没有帮助,因为我得到了其他对象的列表.
Looking for python flatten a list of list didn't help as I got a list of lists of other object.
推荐答案
使用itertools.chain
(或者在这种情况下更好,如niemmi所说的itertools.chain.from_iterable
),避免创建临时列表并使用extend
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)))
小型可复制测试:
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)))
结果:
[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?)
这篇关于Python:展平对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!