简体   繁体   中英

Store the output of a function into a variable

I have the following function that returns data:

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. I'm using print instead of return (in the function get_comments) since, return only returns the final row of my data. 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".

When i try some other value(ie):

 z = hypothetical(5)
 print(z)

z is equal to 5 of course.
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() .

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 :

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. 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.

Refer to this excellent answer for more about yield and generators.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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