gpt4 book ai didi

python - Python Flask中的整数错误

转载 作者:行者123 更新时间:2023-12-03 16:58:39 25 4
gpt4 key购买 nike

我已经实现了一个程序,该程序从url输入以下内容:

lat = float(request.args.get('lat'))
lon = float(request.args.get('long'))


然后,通过Haversine公式,将该经纬度与通过html表单提供的另一组经纬度进行比较,并在ajax对象中捕获为:

objt = {'lat': request.args.get('lat'), 'lon': request.args.get('long')}
sdata.append(objt);
sdatav = json.dumps(sdata):


它返回的输入很好,但是当我尝试比较输入时,出现错误提示:


字符串索引必须是整数,而不是str


在这行上:

distances = (distance(int((v['lat'],v['lon'],lat,lon))) for v in sdatav) 




for lat_lng, d in sorted(zip(sdatav, distances)):


整个代码如下:

@app.route('/')
def home():
objt = {'lat': request.args.get('lat'), 'lon': request.args.get('long')}
sdata.append(objt);
sdatav = json.dumps(sdata)
listlat = []

def distance(lat1, lon1, lat2, lon2):
p = 0.017453292519943295#degree to radian
a = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p)*cos(lat2*p) * (1- cos((lon2-lon1)*p)) / 2
return 12742 * asin(sqrt(a))#print in km

lat = float(request.args.get('lat'))
lon = float(request.args.get('long'))

#Compare the given lat/lon against the set and return values
distances = (distance(v['lat'],v['lon'],lat,lon) for v in sdatav)
for lat_lng, d in sorted(zip(sdatav, distances),key = itemgetter(1)):
lpo = (lat_lng['lat'], lat_lng['lon'],str(d) + "kms" )
listlat.append(lpo)
return listlat
#return json.dumps(sdata)

if __name__ == '__main__':
app.run(port = 5001,debug=True, threaded=True)

最佳答案

根据这个:

sdatav = json.dumps(sdata):


sdatav是一个字符串。您可能想像这样使用 sdata

distances = (distance(float(v['lat']), float(v['lon']), lat, lon) for v in sdata) 

关于python - Python Flask中的整数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49123852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com