TypeError: '<' not supported between instances of 'str' and 'float'

TypeError: '<' not supported between instances of 'str' and 'float'

我有一个简单的 Python 脚本,它查询 API 并解析 JSON 数据。具体来说,我试图根据给定的纬度和经度坐标找到落入矩形的所有 id。我遇到了一些数据类型问题,因为一个作为 str 类型返回,另一个作为 float 类型返回。坐标是:(37.769754, -122.427050)(37.748554, -122.404535).

下面是我的代码、示例 JSON 和轨迹。

代码:

import requests

def get_ids():
    url = "https://retro.umoiq.com/service/publicJSONFeed?command=vehicleLocations&a=sf-muni&t=0"
    response = requests.get(url).json()

    id_list = []

    for id in response['vehicle']:
        lat = id['lat']
        lon = id['lon'] 
        
        if (lat <= 37.769754 and lat >= 37.748554): 
            if (lon >= -122.427050 and lon <= -122.404535):
                id_list.append(id['id'])
    
    return id_list

def main():
    print(get_ids())

if __name__ == "__main__":
    main()

JSON:

{'lastTime': {'time': '1653259435728'}, 'copyright': 'All data copyright San Francisco Muni 2022.', 'vehicle': [{'routeTag': 'KT', 'predictable': 'true', 'heading': '218', 'speedKmHr': '0', 'lon': '-122.405464', 'id': '1462', 'dirTag': 'KT___O_F20', 'lat': '37.708099', 'secsSinceReport': '33', 'leadingVehicleId': '1487'}, {'routeTag': '33', 'predictable': 'true', 'heading': '165', 'speedKmHr': '35', 'lon': '-122.40744', 'id': '5817', 'dirTag': '33___O_F00', 'lat': '37.763451', 'secsSinceReport': '6'}, {'routeTag': '1', 'predictable': 'true', 'heading': '269', 'speedKmHr': '0', 'lon': '-122.492844', 'id': '5818', 'dirTag': '1____O_F00', 'lat': '37.77985', 'secsSinceReport': '33'}, {'routeTag': '1', 'predictable': 'true', 'heading': '219', 'speedKmHr': '0', 'lon': '-122.493156', 'id': '5819', 'lat': '37.779823', 'secsSinceReport': '6'}, {'routeTag': 'N', 'predictable': 'true', 'heading': '195', 'speedKmHr': '6', 'lon': '-122.457748', 'id': '1453', 'dirTag': 'N____O_F01', 'lat': '37.764671', 'secsSinceReport': '33'}, {'routeTag': '24', 'predictable': 'true', 'heading': '231', 'speedKmHr': '0', 'lon': '-122.412033', 'id': '5813', 'dirTag': '24___I_F00', 'lat': '37.739773', 'secsSinceReport': '20'}, {'routeTag': '1', 'predictable': 'true', 'heading': '80', 'speedKmHr': '0', 'lon': '-122.397522', 'id': '5815', 'dirTag': '1____I_F00', 'lat': '37.795418', 'secsSinceReport': '46'}, {'routeTag': '1', 'predictable': 'true', 'heading': '87', 'speedKmHr': '0', 'lon': '-122.472931', 'id': '5827', 'dirTag': '1____I_F00', 'lat': '37.78437', 'secsSinceReport': '6'}, {'routeTag': 'KT', 'predictable': 'true', 'heading': '330', 'speedKmHr': '32', 'lon': '-122.468117', 'id': '1469', 'dirTag': 'KT___I_F20', 'lat': '37.7290149', 'secsSinceReport': '6'}, {'routeTag': '33', 'predictable': 'true', 'heading': '77', 'speedKmHr': '0', 'lon': '-122.456421', 'id': '5828', 'dirTag': '33___O_F00', 'lat': '37.786957', 'secsSinceReport': '6'}, {'routeTag': '45', 'predictable': 'true', 'heading': '165', 'speedKmHr': '21', 'lon': '-122.406647', 'id': '5829', 'dirTag': '45___I_F00', 'lat': '37.78756', 'secsSinceReport': '6'}
etc...

跟踪:

Traceback (most recent call last):
  File "/main.py", line 51, in <module>
    main()
  File "/main.py", line 48, in main
    get_ids()
  File "/main.py", line 41, in get_ids
    if (lat < 37.769754 and lon < -122.427050): 
TypeError: '<' not supported between instances of 'str' and 'float'

尝试像这样将数据转换为浮点数:

lat = float(i['lat'])
lon = float(i['lon'])

这将允许比较运算符在比较 2 个浮点数时正确工作。

请记住运算符本身是错误的(long -179 和 lat -179 将适合您的矩形)。


我冒昧地改进了您的一些代码并修复了比较运算符:

import requests

VEHICLE_LOCATIONS_URL = "https://retro.umoiq.com/service/publicJSONFeed?command=vehicleLocations&a=sf-muni&t=0"
# (min_lat, max_lat), (min_long, max_long)
BOUNDARIES = ((37.748554, 37.769754), (-122.427050, -122.404535))

def get_ids_in_boundry():
    response = requests.get(VEHICLE_LOCATIONS_URL).json()

    id_list = []

    for vehicle in response['vehicle']:
        lat, long = float(vehicle['lat']), float(vehicle['lon'])

        if ((BOUNDARIES[0][0] <= lat <= BOUNDARIES[0][1])
            and (BOUNDARIES[1][0] <= long <= BOUNDARIES[1][1])):
            id_list.append(vehicle['id'])

    return id_list

def main():
    print(get_ids_in_boundry())

if __name__ == "__main__":
    main()

我已将 URL 更改为常量,作为边界,并在函数外部返回了 id_list。可以添加许多其他改进,例如在函数参数中请求边界或将请求和边界检查拆分为 2 个不同的函数。

如果我理解正确,答案是将变量 latlon 转换为浮点数。

要做到这一点,只需在您的代码中进行修改

lat = float(i['lat'])
lon = float(i['lon'])