[英]Pandas Python - How to reorder second level row indexes according to a specific list of labels
[英]Reorder a tree node according to specific attribute in python
简单树的代码
class A_1:
saveable =True
class A_2:
saveable =False
class B_1:
saveable =True
class B_2:
saveable =False
class C_1:
saveable =False
class C_2:
saveable =True
class A:
saveable = True
inline = [A_1,A_2]
class B:
saveable = False
inline = [B_1,B_2]
class C:
saveable = True
inline = [C_1,C_2]
class Main:
inline =[A,B,C]
我想要一个 function 或根据可保存属性对节点进行排序的方法。 我想要 output 像:
>>Main.inline
[B, C, A]
>>A.inline
[A_2,A_1]
等等
虽然我不同意这种方法,但这是您需要做的:(我尽可能少地修改了代码,并在底部添加了测试以证明它有效)
import operator
class A_1:
saveable =True
class A_2:
saveable =False
class B_1:
saveable =True
class B_2:
saveable =False
class C_1:
saveable =False
class C_2:
saveable =True
class Ordered(type):
def __new__(cls, name, bases, attr):
new_klass = super(Ordered, cls).__new__(cls, name, bases, attr)
# Uncomment the line bellow after you've read the comment in all the
# way at the bottom of the code.
#
# new_klass.inline.sort(key=lambda x: x.__name__, reverse=True)
new_klass.inline.sort(key=operator.attrgetter('saveable'))
return new_klass
class A(metaclass=Ordered):
saveable = True
inline = [A_1,A_2]
class B(metaclass=Ordered):
saveable = False
inline = [B_1,B_2]
class C(metaclass=Ordered):
saveable = True
inline = [C_1,C_2]
class Main(metaclass=Ordered):
inline =[A,B,C]
# this differs from your example slightly, since you asked
# for `[B, C, A]`, in order to get that working, is just a
# matter of changing the `sort()` above, and uncommenting
# the commented line in the function. I left it there in
# case you REALLY wanted it. I figured this would be enough
# and the alternative just complicates things further
assert Main.inline == [B, A, C]
# assert Main.inline == [B, C, A]
assert A.inline == [A_2, A_1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.