首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python列表的复杂排序算法?

Python列表的复杂排序算法?
EN

Stack Overflow用户
提问于 2011-08-19 17:15:32
回答 1查看 174关注 0票数 1

我需要订购一个注释的list,以便它们以线程的顺序出现。

每一条评论都有:

queries)

  • Parent comment

  • Indentation

  • 顶级父级注释(用于

)

如果我以list的形式获取注释,那么排序它的最有效方法是在父下面的

It 必须将保持为一维列表.我只想重新安排物品。我正在尝试这个方法,但是它不起作用,因为列表在enumaration过程中发生了变异,打破了计数器:

代码语言:javascript
运行
复制
i = 0;
for child in childList:
    ii = 0;
    for ch in childList:
        if (ch.reply == child.id):
            childList.insert(i+1, childList.pop(ii))

    ii += 1;
    i += 1;
EN

回答 1

Stack Overflow用户

发布于 2011-08-19 17:27:50

我建议您更改/创建一个包含注释信息的Comment类以及其子类的列表。然后循环遍历您的列表,并创建注释作为Comment对象的字典。循环,这一次将每个注释添加到父对象。最后,遍历字典,选择没有父母的注释,这些都是您的顶级评论。这些Comment对象包含对所有其他注释的引用!

下面是一些代码,说明了我的意思,并将最终的注释对象放在一个一维列表中:

代码语言:javascript
运行
复制
class Comment:
    def __init__(self, _id, parent):
        self.id, self.parent = _id, parent
        self.children = []

comments = [
    [1, None], # id, parent
    [2, 1],
    [3, None],
    [4, 2],
    [5, 3],
]

# store comments by their ID, as Comment objects
comments_dict = {}
for comment in comments:
    comments_dict[comment[0]] = Comment(*comment)

# store top level comments, and add child comments to their parent objects
top_comments = []
for _id, comment in comments_dict.items():
    if comment.parent != None:
        comments_dict[comment.parent].children.append(comment)
    else:
        top_comments.append(comment)

# final list of comments
comments = []
def add_comment(comment):
    """Recursively add comments to final list"""
    global comments
    comments.append(comment)
    if comment.children:
        for child in comment.children:
            add_comment(child)

for comment in top_comments:
    add_comment(comment)

print [comment.id for comment in comments]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7125082

复制
相关文章

相似问题

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