![](/img/trans.png)
[英]How to Store the Output of a system return function in a string variable in python/tkinter
[英]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.