繁体   English   中英

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

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

因此,我尝试了使用循环运行的JSON文件中的数据返回数据的不同方法。

我的想法是,我有一个带有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))

我看不到或想不出如何获取临时数据并将其保存到外部变量。 我试图制作一个调用for循环的变量,但对我来说也失败了。

编辑:被称为此帖子的副本 但这不包括for循环的返回。

您需要将值保存到某些数据结构-列表,字典等:

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)

正如@ggorlen所提到的,打印结果似乎是您最终想要做的,因此我在循环中添加了一条print语句。

确保在循环外部建立数据结构,因为否则,您将在每个循环上覆盖变量。

暂无
暂无

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

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