python中嵌套while循环的效率有多低?

2024-10-01 17:29:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图返回一个评论列表到Facebook的帖子。在某些情况下,注释本身也有回复,这些回复在JSON的嵌套列表中,我将其作为“commentraw”。我不想只返回JSON所使用的原始数据和格式,在某些情况下,我会进行转换或重组。我相信评论和回复的数据格式是一样的,但回复并不总是出现。不管怎样,为了实现这一点,我提出了以下函数:

def get_post_comments(commentraw, graphsession):
    graph=graphsession
    commentlist=[]
    i=0

    while(i<len(commentraw['data'])):
        entry={'id': commentraw['data'][i]['id'], 'created_time': convert_date(commentraw['data'][i]['created_time']), 'message': commentraw['data'][i]['message']}
        replyraw=graph.get_connections(id=commentraw['data'][i]['id'], connection_name='comments', summary=True)
        if replyraw['data']:#if theres replies to the comment on the post, do a nested while (yuck) to also grab and format the replies - this is probably insanely inefficient
            y=0
            replylist=[]
            while(y<len(replyraw['data'])):
                subentry={'created_time': convert_date(replyraw['data'][y]['created_time']), 'id': replyraw['data'][y]['id'], 'message': replyraw['data'][y]['message'], 'from': replyraw['data'][y]['from']}
                replylist.append(subentry)
                y=y+1
            entry['replies']=replylist
        commentlist.append(entry)
        i=i+1

    return commentlist

基本上,因为这是一个JSON输入,包含N个注释或回复的列表,所以我使用while循环和增量来确保迭代列表中的所有项。但是,因为对注释的回复是嵌入在JSON中的,所以我必须在while循环中嵌入while循环来迭代所有可能的数据。你知道吗

Facebook可能拥有大量数据。我的解决方案效率有多低(即嵌套while循环)?我有一个潜在的怀疑,递归可能在这里,但我是一个新手Python编码器。你知道吗


Tags: theidjsonmessage列表datatimeentry

热门问题