查询提名时如何支持“镇”和“市”?

2024-07-04 16:53:53 发布

您现在位置:Python中文网/ 问答频道 /正文

使用namitm的反向地理编码似乎根据位置的大小返回“town”或“city”。你知道吗

import geojson
from geopy.geocoders import Nominatim

location = "48.84837905, 2.28229522311902"
geolocator = Nominatim(user_agent="my-application",timeout=3)
location = geolocator.reverse(location)
print(location.raw)
#Sometimes "town", sometimes "city"
##print(location.raw['address']['town'])
##print(location.raw['address']['city'])

处理这两种情况的好方法是什么?你知道吗

谢谢你。你知道吗


Tags: fromimportcity编码rawaddressgeojsonlocation
1条回答
网友
1楼 · 发布于 2024-07-04 16:53:53

这正是try-except的目的:

try:
    print(location.raw['address']['town'])
except KeyError:
    print(location.raw['address']['city'])

备选方案

一些注重性能的人会说“但是尝试是昂贵的”。你知道吗

您可以使用其他替代方案:

  • if 'town' in location.raw['address']: ... else: ...
  • location.raw['address'].get('town', location.raw['address'].get('city'))

每种方法都有其优缺点。^例如,{}并不懒惰。location.raw['address'].get('city')将 在查找'town'之前进行评估,因此事实上,它比 浪费的和适得其反的。 if-else方法(取决于它的使用方式)可能需要对其中一个键进行两次哈希运算。你知道吗

我认为在try块中放置更常见的键就足够了。你知道吗

让我们做一些测试:

from timeit import Timer
from random import choice

list_of_dicts = [{choice(('town', 'city')): 1} for _ in range(2000)]

def try_except():
    for d in list_of_dicts:
        try:
            d['town']
        except KeyError:
            d['city']

def if_else():
    for d in list_of_dicts:
        if 'town' in d:
            d['town']
        else:
            d['city']

def get():
    for d in list_of_dicts:
        d.get('town', d.get('city'))


print(min(Timer(try_except).repeat(10, 10)))
print(min(Timer(if_else).repeat(10, 10)))
print(min(Timer(get).repeat(10, 10)))

这个输出

0.0053282611981659705
0.0018278721105344786
0.00536558375274554

这意味着在这个2000个字典的例子中,if-else是最快的(即使它需要对其中一个键进行两次散列),而try-exceptget是差不多的。你知道吗

相关问题 更多 >

    热门问题