首页 > 解决方案 > 迭代字符串的一部分

问题描述

我想提取一些我有以下代码的数据:

import http.client

conn = http.etc("something")

headers = {
    'id': "asdfghjk",
    'accept': "application/json"
    }

conn.request("GET", "/SomeLocationData?latitude=50&longitude=10&time=631152000", headers=headers)

res = conn.getresponse()
data = res.read()

print(data.decode("utf-8"))

现在,我想提取从纬度 45 到 55 的所有数据,经度和时间也是如此。所以对于每一个我都有一个范围,我需要所有可能的组合。如何为该字符串中的每个值编写一个 for 循环?

编辑:这是我用来从服务中提取数据的代码,我只输入纬度、经度和时间的值。输出类似于:

[{"contentVersion":1,"location":{"latitude":48.003,"longitude":15.998001,"time":1597287600},"precipitation":-999,"symbolCode":-999,"temperature":15,"windDirection":190.22656,"windSpeed":0.015625}]

标签: pythonjsonstringfor-loop

解决方案


正如大家所说,这取决于您从 GET 方法获得的数据,到目前为止,为了更好地理解,我将展示以下示例 JSON。

让我们考虑这是我们从 GET 方法获得的输出。

[
{
    "contentVersion": 1,
    "location": {
        "latitude": 48.003,
        "longitude": 15.998001,
        "time": 1597287600
    },
    "precipitation": -999,
    "symbolCode": -999,
    "temperature": 15,
    "windDirection": 190.22656,
    "windSpeed": 0.015625
},
{
    "contentVersion": 2,
    "location": {
        "latitude": 58.003,
        "longitude": 5.998001,
        "time": 1297287600
    },
    "precipitation": -999,
    "symbolCode": -999,
    "temperature": 15,
    "windDirection": 190.22656,
    "windSpeed": 0.015625
},
{
    "contentVersion": 1,
    "location": {
        "latitude": 40.003,
        "longitude": 51.998001,
        "time": 1097287600
    },
    "precipitation": -999,
    "symbolCode": -999,
    "temperature": 15,
    "windDirection": 190.22656,
    "windSpeed": 0.015625
    }
]

下面是我们可以为各个值获取的代码。

for x in range(len(data)):
    lati = int(data[x]['location']['latitude'])
    
    # Getting Latitude on a range
    if lati > 45 and lati > 50:
        print(lati)
        
    # Same way for the other two

对于使用上述 JSON 的上述代码,Latitude 的输出将仅为 58。


推荐阅读