簡體   English   中英

根據 python 中的特定屬性重新排序樹節點

[英]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]

等等

如果我們 plot output 是一樣的: 必需的

雖然我不同意這種方法,但這是您需要做的:(我盡可能少地修改了代碼,並在底部添加了測試以證明它有效)

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM