我有具有属性的评论列表:(pk
主键),parent_pk
(父键的主键)和其他...我想在嵌套方面显示它们 - 如果评论有孩子,显示评论,然后是缩进更多的孩子. 当评论与其他评论pk
相同时,评论是其他评论的子评论parent_pk
。
我最初将在我的 Django 博客中实现它,但首先我想学习如何做。这就是为什么为了简单起见,我创建了 CLI 应用程序。我知道那里有现成的解决方案,但我想学会自己做。:)
这是我现在的代码:
class Comment(object):
def __init__(self, pk, parent_pk, content):
self.pk = pk
self.parent_pk = parent_pk
self.content = content
def has_children(self, comments):
for comment in comments:
if self.pk == comment.parent_pk:
return True
return False
def get_children(self, comments):
children = []
for comment in comments:
if self.pk == comment.parent_pk:
children.append(comment)
return children
def print_nested(comments, level=0):
def to_whitespaces(level):
if level == 0:
return ""
else:
return " " * (level * 2)
for comment in comments:
print to_whitespaces(level) + comment.content
if comment.has_children(comments):
print_nested(comment.get_children(comments), level + 1)
comments.pop(0)
comments = [
Comment(1, None, "foo"),
Comment(2, 1, "foo bar"),
Comment(3, None, "spam"),
Comment(4, 3, "spam cheese"),
Comment(5, 4, "spam cheese monty"),
Comment(6, None, "muse"),
]
print_nested(comments)
预期结果:
foo
foo bar
spam
spam cheese
spam cheese monty
muse
实际结果:
foo
foo bar
spam
spam cheese
spam cheese monty
muse
如您所见,spam cheese monty
它根本没有缩进。任何想法为什么会这样?你将如何实施它?谢谢!