首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >根据python中的特定属性重新排序树节点

根据python中的特定属性重新排序树节点
EN

Stack Overflow用户
提问于 2021-01-04 15:01:21
回答 1查看 60关注 0票数 3

简单树代码

代码语言:javascript
运行
复制
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]

代码图是:

我想要一个函数或方法来根据保存属性对节点进行排序。我想要的输出如下:

代码语言:javascript
运行
复制
>>Main.inline
[B, C, A]

>>A.inline
[A_2,A_1]

诸若此类

如果我们绘制的输出是相同的,如下所示:

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-05 15:23:29

虽然我不同意的方法,但这是您需要做的:(我尽可能少地修改了代码,并在底部添加了测试以证明它有效)

代码语言:javascript
运行
复制
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]
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65564879

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档