我需要订购一个注释的list
,以便它们以线程的顺序出现。
每一条评论都有:
queries)
)
如果我以list
的形式获取注释,那么排序它的最有效方法是在父下面的
It 必须将保持为一维列表.我只想重新安排物品。我正在尝试这个方法,但是它不起作用,因为列表在enumaration过程中发生了变异,打破了计数器:
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;
发布于 2011-08-19 17:27:50
我建议您更改/创建一个包含注释信息的Comment
类以及其子类的列表。然后循环遍历您的列表,并创建注释作为Comment
对象的字典。循环,这一次将每个注释添加到父对象。最后,遍历字典,选择没有父母的注释,这些都是您的顶级评论。这些Comment
对象包含对所有其他注释的引用!
下面是一些代码,说明了我的意思,并将最终的注释对象放在一个一维列表中:
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]
https://stackoverflow.com/questions/7125082
复制相似问题