繁体   English   中英

将一个function的output存储到一个变量中

[英]Store the output of a function into a variable

我有以下返回数据的 function:

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']
    print(comment)

我想把这个function的output保存到一个变量中。 我使用打印而不是返回(在 function get_comments 中),因为返回只返回我数据的最后一行。 这就是我试图解释的:

def hypothetical(x):
return x

z = hypothetical(get_comments())
print(z)

然而,变量 z 的 output 是“无”。

当我尝试其他一些值时(即):

 z = hypothetical(5)
 print(z)

z当然等于5。
谢谢

无需打印每一行,您需要将其添加到不同的数据结构(例如列表)并在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

如果你想更高级一点,你可以使用yield创建一个generator

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()并且它每次都会将 go 返回到生成器中以获取下一条评论。 或者您可以简单地将生成器转换为带有list(get_comments())的列表,以便返回到您想要的评论列表。

有关yield和生成器的更多信息,请参阅这个出色的答案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM