python | 您所在的位置:网站首页 › print函数输出 › python |
您需要将其添加到其他数据结构(例如列表)中,而不是打印每一行,并在get_comments()的末尾返回整个列表。 例如: def get_comments(): to_return = [] for i in data: comment_data = i['comments'] for z in comment_data: comments = comment_data['data'] for j in comments: comment = j['message'] to_return.append(comment) return to_return如果您想提高一点,可以改为使用generator创建一个yield: def get_comments(): for i in data: comment_data = i['comments'] for z in comment_data: comments = comment_data['data'] for j in comments: comment = j['message'] yield comment然后,您可以遍历get_comments(),每次它将返回生成器以获取下一个注释。或者,您可以简单地将生成器转换为带有list(get_comments())的列表,以返回所需的评论列表。 有关yield和生成器的更多信息,请参考this excellent answer。 |
CopyRight 2018-2019 实验室设备网 版权所有 |