for循环只迭代集合中的最后一个值

l0oc07j2  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(342)
import datetime as dt
import pandas as pd
import pandas_datareader as pdr
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as dates
import numpy as np

# import natlparks as pnp

import geopandas as gpd
import geopy as gp
import googlemaps as gm
import shapely
import scipy
import geopy.distance
from geopy.geocoders import Nominatim
from shapely.geometry import Point
from shapely.ops import nearest_points
from scipy.spatial import cKDTree
import scipy.spatial as spatial

# import streamlit as st

# st.title("Finding NY National Parks Near You")

def close_by(pt, location):
    data = pd.read_csv('National_Register_of_Historic_Places (3).csv')
    close_locations = []
    location_latitude = float(location.latitude)
    location_longitude = float(location.longitude)
    #for index, row in data.itterrows():
    close_locations = [shapely.geometry.Point(lon, lat) for lon,lat in zip(data['Longitude'], data['Latitude'])]
    gdf = gpd.GeoDataFrame(data, geometry=close_locations, crs={"init":"EPSG:4326"})
    pts = gdf.geometry.unary_union
    ptsArray = np.array(pts)
    print(ptsArray)
    point_tree = spatial.KDTree(ptsArray)
    query = point_tree.query_ball_point([location.longitude, location.latitude], 1)
  **for i in range(len(query)):
        lst = []
        otherList=[]
        value = query[i]
        lst.append(gdf.iloc[value])**
def main():
    data = pd.read_csv('National_Register_of_Historic_Places (3).csv')
    streetNum = input("Enter your number")
    streetName = input("Enter Your Street Name")
    city = input("Enter your city")
    geolocator = Nominatim(user_agent="Final_Project_Python")
    location = geolocator.geocode(f"{streetNum} {streetName} {city} ")
    print(location.address)
    print(location.latitude, location.longitude)
    pt = Point(location.longitude, location.latitude)
    print(float(location.latitude))
    print(float(location.longitude))
    close_by(pt, location)
main()

我在close\u by函数中粗体显示的for循环当前只返回查询的最后一个值,而不是它之前的所有记录。有人知道如何让它包含所有它迭代的值,而不是每次都覆盖上一个值吗?

uemypmqf

uemypmqf1#

列表应该在for循环之外,否则lst的每个循环都将替换为[]

lst = []
otherList=[]
for i in range(len(query)):

    value = query[i]
    lst.append(gdf.iloc[value])
eufgjt7s

eufgjt7s2#

因为您将lst=[]放入for循环中,所以每次它运行时,都会清空列表。试试这个:

lst = []
    for i in range(len(query)):
      otherList=[]
      value = query[i]
      lst.append(gdf.iloc[value])

相关问题