1

I have a list of class instances like so:

classes = [A(someval), B(someval), C(someval)]

I would like to sort this list using a "master" list.

master_list = [B, A]

This would sort the list with B and A first if they exist and always in the order specified in master_list. The classes are field validators so I expect there never to be more than one of each class, but one can never know for sure.

Any other class instances can just come after in any order they appear.

I would like to be able to put some instances at the end of the list according to another master list, but I suspect the best this to do here is just reverse the list and do the same thing again.

But how do I do it?

Edit: Subclasses are not important as these validator classes only have a single callable method and are generally pretty simple beasts. I have yet to encounter a subclassed validator and I have tried to imagine a scenario where it would be beneficial, but I cannot.

4

2 回答 2

5

您可以使用index列表类的功能。这是一个简单的例子:

class A: pass
class B: pass
class C: pass

classes = [A(), B(), C()]
master_list = [B, A]

def sorter(instance):
    # get the type of the object
    c = instance.__class__
    # if it is in the master_list, use its index, otherwise put it at the end
    return master_list.index(c) if c in master_list else len(master_list)

final_list = sorted(classes, key=sorter)

final_list 现在是

[<__main__.B instance at 0x023348C8>, <__main__.A instance at 0x01EE64B8>, <__main__.C instance at 0x023348F0>]
于 2013-07-12T12:38:15.457 回答
3
def class_order(master_list):
    master_dict = { cls:i for (i, cls) in enumerate(master_list) }
    return lambda i: master_dict.get(i.__class__, len(master_list))

# I renamed ‘classes’ to ‘instances’ because it makes more sense.
sorted(instances, key=class_order(master_list))

这假设只有 master_list 中类的直接实例出现在原始列表中。如果出现从 A 或 B 派生的内容,它们将不会排序为 As 或 Bs,它们应该这样做。

于 2013-07-12T12:41:50.223 回答