简体   繁体   English

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

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

I have the following function that returns data:我有以下返回数据的 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)

I would like to save the output of this function to a variable.我想把这个function的output保存到一个变量中。 I'm using print instead of return (in the function get_comments) since, return only returns the final row of my data.我使用打印而不是返回(在 function get_comments 中),因为返回只返回我数据的最后一行。 This is what i have tried to account for that:这就是我试图解释的:

def hypothetical(x):
return x

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

However the output of the variable z is "None".然而,变量 z 的 output 是“无”。

When i try some other value(ie):当我尝试其他一些值时(即):

 z = hypothetical(5)
 print(z)

z is equal to 5 of course. z当然等于5。
Thanks谢谢

Instead of printing each line, you need to add it to a different data structure (such as a list) and return the whole list at the end of get_comments() .无需打印每一行,您需要将其添加到不同的数据结构(例如列表)并在get_comments()的末尾返回整个列表。

For example:例如:

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

If you want to get a bit more advanced, you can instead create a generator using yield :如果你想更高级一点,你可以使用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

Then you can iterate over get_comments() and it will go back into the generator each time to get the next comment.然后你可以迭代get_comments()并且它每次都会将 go 返回到生成器中以获取下一条评论。 Or you could simply cast the generator into a list with list(get_comments()) in order to get back to your desired list of comments.或者您可以简单地将生成器转换为带有list(get_comments())的列表,以便返回到您想要的评论列表。

Refer to this excellent answer for more about yield and generators.有关yield和生成器的更多信息,请参阅这个出色的答案

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

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