将函数的输出存储到变量中

CS.*_*.py 0 python 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)
Run Code Online (Sandbox Code Playgroud)

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

def hypothetical(x):
return x

z = hypothetical(get_comments())
print(z)
Run Code Online (Sandbox Code Playgroud)

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

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

 z = hypothetical(5)
 print(z)
Run Code Online (Sandbox Code Playgroud)

z当然等于5。
谢谢

tbu*_*s13 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
Run Code Online (Sandbox Code Playgroud)

如果你想更高级一点,你可以创建一个generatorusing 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
Run Code Online (Sandbox Code Playgroud)

然后你可以迭代get_comments(),它每次都会回到生成器中以获取下一条评论。或者您可以简单地将生成器转换为一个列表,list(get_comments())以便返回到您想要的评论列表。

有关生成器的更多信息,请参阅此优秀答案yield