我有意見列表,其中有:pk
(主鍵),parent_pk
(父母的主鍵)和其他人...我想顯示他們W /尊重嵌套 - 如果評論有孩子,則顯示評論,然後顯示更多的孩子。評論是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)
Here's it on Sprunge.us (w/ syntax).
預期結果:
foo
foo bar
spam
spam cheese
spam cheese monty
muse
實際結果:
foo
foo bar
spam
spam cheese
spam cheese monty
muse
正如你所看到的, spam cheese monty
根本沒有縮進。任何想法爲什麼這樣?你將如何實現它?謝謝!
哇,這真是太棒了!我不太明白...... 1.不是在打印函數中做遞歸,而是爲'Comment'創建新的方法,它通過'comments'列表中的所有註釋(有點奇怪,你不會將它作爲參數傳遞給'depth()'方法)並遞歸發現評論的深度? 2.如果主鍵會被搞亂(任何順序),這個解決方案是否會工作? – daGrevis
@daGrevis正如我在文章和評論中提到的那樣,您應該在評論中構建一棵樹,並使用該數據結構來查找父母。這將消除對列表中評論順序的敏感性。我只是沒有爲你寫這部分,因爲我可以說明你的列表計算深度的一般方法,因爲pks和索引恰好相關。 – agf