按对象类型拆分包含对象的python列表

时间:2019-07-16 08:41:09

标签: python python-3.x list

我尝试了以下操作,看来它可以正常工作。问题是这是pythonic方式吗?我的实际代码在继承方面非常复杂。我正在尝试检查并将更新。谢谢

class A:
    def __repr__(self):
        return "A"

class B:
    def __repr__(self):
        return "B"

class C:
    def __repr__(self):
        return "C"

def split_by_type(object_list, obj_type):
    final, inter = [], []
    for obj in object_list:
        if isinstance(obj, obj_type):
            if inter:
                final.append(inter)
            inter = [obj]
        else:
            inter.append(obj)
    final.append(inter)
    return final

输入[A1, B1, C1, A2, B2, A3, C3, A4, B4, C4]

输出[[A1, B1, C1], [A2, B2], [A3, C3], [A4, B4, C4]]

object_list = [A(), B(), C(), A(), B(), A(), C(), A(), B(), C()]
print(split_by_type(object_list, A)) # ==> [[A, B, C], [A, B], [A, C], [A, B, C]]

1 个答案:

答案 0 :(得分:2)

您可以使用itertools.groupbyitertools.count

object_list = [A(), B(), C(), A(), B(), A(), C(), A(), B(), C()]

from itertools import groupby, count

c = count()
out = [[o[1] for o in g] for v, g in groupby(enumerate(object_list), lambda o: o[0]-[next(c), next(c)][-1] if isinstance(o[1], A) else o[0]-next(c))]

print(out)

打印:

[[A, B, C], [A, B], [A, C], [A, B, C]]