给定
post = {"comments": [
{
"_id": 2,
"detail": "info1",
"responses": [
{
"_id": 3,
"responses": [],
"detail": "info2"
}]
},
{
"_id": 0,
"responses": [],
"detail": "info3",
}]
}
从视觉上看,这只是
[comment comment]
[child comment]
[parent comment]
我正试图遍历从第一条到最后一条的每条评论
所以info1然后info2然后info3
我的尝试
queue = []
comment1 = post['comments']
queue.append(comment1)
for responses in queue:
for comment in responses:
print(comment['detail'])
if(comment['responses'] != []):
queue.append(comment['responses'])
这会打印
info1
info3
info2
不管怎样,通过调整一下来得到我想要的?
您可以使用递归函数遍历注释树。有一种方法:
def replies_deep(comment):
print(comment['detail'])
for response in comment['responses']: # Iterate over responses
replies_deep(response) # Recurse into the response's responses
for top in post['comments']:
replies_deep(top)
您的代码之所以这么做,是因为它在队列的末尾添加了回复,而不是直接在它后面。要解决这个问题,您需要创建一个函数:
def process_comment(comment):
print(comment['detail'])
if(comment['responses'] != []):
for i in comment['responses']:
process_comment(i)
queue = []
comment1 = post['comments']
queue.append(comment1)
for responses in queue:
for comment in responses:
process_comment(comment)
上面的代码应该可以工作。
试试这个代码;它使用递归函数来获取注释:
#Bad code, but simplest in this circumstance.
def iterate(arr):
global queue
for comment in arr:
queue.append(comment["detail"])
print(comment["detail"]) #For your debug.
iterate(comment["responses"])
post = {} #Put your data here
queue = []
iterate(post["comments"])
该函数反复调用自己,读取对答复的答复,直到完成为止。它会产生你想要的结果,在穿过之前先下树。