首页 > 解决方案 > 有没有办法用这段代码遍历一个列表?

问题描述

基本上,我有一个大约 5,000 个纬度和经度的列表,我想分别循环并运行这个查询。我一直在手动执行此操作并单独运行查询,但我想必须有一种方法来标准化该过程。非常感谢任何帮助或想法,谢谢!

df = []

places_result = gmaps.places(query=query, location=(latitude1, longitude1), radius=32186.9, )

for place in places_result['results']:
    my_place_id = place['place_id']

    my_fields = ['name', 'business_status', 'formatted_address', 'opening_hours', 'rating', 'website',
                 'formatted_phone_number', 'geometry/location/lng', 'geometry/location/lat']

    place_details = gmaps.place(place_id=my_place_id, fields=my_fields)

    column_names = ['name', 'rating', 'address', 'website', 'phone', 'status', 'hours', 'lat', 'lng']

    # df=pd.DataFrame(columns = column_names)

    try:
        rating = place_details['result']['rating']
    except KeyError:
        rating = 'na'
    try:
        name = place_details['result']['name']
    except KeyError:
        name = "na"
    try:
        address = place_details['result']['formatted_address']
    except KeyError:
        address = "na"
    try:
        website = place_details['result']['website']
    except KeyError:
        website = "na"
    try:
        phone = place_details['result']['formatted_phone_number']
    except KeyError:
        phone = "na"
    try:
        lat = place_details['result']['geometry']['location']['lat']
    except KeyError:
        lat = "na"
    try:
        lng = place_details['result']['geometry']['location']['lng']
    except KeyError:
        lng = "na"
    try:
        status = place_details['result']['business_status']
    except KeyError:
        status = "na"
    try:
        hours = place_details['result']['opening_hours']
    except KeyError:
        hours = 'na'

    df1 = {"name": [name, ], "rating": [rating, ], "address": [address, ], "website": [website, ], "phone": [phone, ],
           "status": [status, ], "hours": [hours, ], "lat": [lat, ], "lng": [lng, ]}
    data: DataFrame = pd.DataFrame(data=df1)
    df.append(data)
dfr = pd.concat(df)

标签: pythonloopsgoogle-maps

解决方案


首先,关于你的尝试,除了块,你可以用以下方式重写那些:

result = place_details['result']

rating = result.get('rating', 'na')
name = result.get('name', 'na')
...

等等。dict.get(key, default=None) 方法将避免引发 KeyError 并且您可以在您的情况下提供默认值“na”。

您可以通过字典理解进一步缩小它:

keys = ["name", "rating", "address", "website", "phone",
        "status", "hours", "lat", "lng"]
entry = {k: result.get(k, 'na') for k in keys}

假设您在两个列表中有您的 lat 和 lon 值:

entries = []
for lat, lon in zip(latitudes, longitudes):
    q = gmaps.places(query=query, location=(lat, lon), radius=32186.9,)
    result = q.get('result', {})  # returns an empty dict if the query fails
    entry = {k: result.get(k, 'na') for k in keys}
    entries.append(entry)

df = pd.DataFrame(entries)  # create a pandas dataframe

推荐阅读