简体   繁体   English

我如何使for循环从函数返回值

[英]How do i make the for loop return the value from a function

So I have tried different methods of returning the data using data from a JSON file running in a loop. 因此,我尝试了使用循环运行的JSON文件中的数据返回数据的不同方法。

The idea is that I have a config.json file with ip`s that need to be feed to the function when its called upon. 我的想法是,我有一个带有ip的config.json文件,需要在调用该文件时将其提供给函数。

{
    "ip1" : "10.0.0.111",
    "ip2" : "10.0.0.112"
  }
import json
import urllib.request

with open('config.json') as config_file:
    data = json.load(config_file)

def temprature(v):

    urlData = f"http://{v}:8080/getdevice?device=type28_1"
    #print(urlData)
    webURL = urllib.request.urlopen(urlData)
    data = webURL.read()
    encoding = webURL.info().get_content_charset('utf-8')
    tempData = json.loads(data.decode(encoding))
    return tempData["Celsius"]


for (k, v) in data.items():
   #print("Key: " + k)
   temprature(v)
   #print(str(v))

I can`t see or figure out how I can fetch the tempdata and save it to an external variable. 我看不到或想不出如何获取临时数据并将其保存到外部变量。 I have tried to make a variable that calls the for loop but that failed for me as well. 我试图制作一个调用for循环的变量,但对我来说也失败了。

Edit: Being referred to as a duplicate of This post. 编辑:被称为此帖子的副本 But this does not cover the return from a for loop. 但这不包括for循环的返回。

You need to save the value to some data structure - list, dictionary, whatever: 您需要将值保存到某些数据结构-列表,字典等:

temperature_data = []
for (k, v) in data.items():
   #print("Key: " + k)
   temperature_data.append(temprature(v))
   #print(str(v))
    print(temprature(v))

print(temperature_data)

temperature_data = {}
for (k, v) in data.items():
   #print("Key: " + k)
   temperature_data[k] = temprature(v)
   #print(str(v))
   print(temprature(v))

print(temperature_data)

as @ggorlen mentioned, it seems that printing the results is what you'd like to ultimately do, so I added a print statement in the loop. 正如@ggorlen所提到的,打印结果似乎是您最终想要做的,因此我在循环中添加了一条print语句。

Make sure to establish the data structure outside of the loop, because otherwise, you'll be writing over the variable on each loop. 确保在循环外部建立数据结构,因为否则,您将在每个循环上覆盖变量。

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

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