【问题标题】:Loop only reads the first row循环只读取第一行
【发布时间】:2021-04-18 10:39:49
【问题描述】:

我有一个用 Folium 创建地图的循环,输入是数据库“s”,但它只读取第一行。有什么东西正在停止循环。

可能是缩进问题。

代码工作如下,首先我们检查目录中是否有下载的照片,如果正确,我们将这张照片用于Folium弹出窗口并添加功能。如果我们没有照片,我们会抓取它,将照片下载到目录中,将其用于弹出窗口并添加一个功能。

def create_geojson_features(s):

features = []

for _, row in s.iterrows():
    if os.path.isfile('/Users/Alberto/Desktop/Oscar/UNIVERSIDAD/TFG/test_inicial/out/IMO_photos/' + row['IMO'].__str__() + '.jpg'):
        image = '/Users/Alberto/Desktop/Oscar/UNIVERSIDAD/TFG/test_inicial/out/IMO_photos/' + row['IMO'].__str__() + '.jpg'
        print("photo OK!")
        feature = {
            'type': 'Feature',
            'geometry': {
                'type':'Point',
                'coordinates':[row['lon'],row['lat']]
            },
            'properties': {
                'time': pd.to_datetime(row['date']).__str__(),
                'popup': "<img src=" + image.__str__() + " width = '250' height='200'/>"+'<br>'+'<br>'+'Shipname: '+row['shipname'].__str__() +'<br>'+ 'MMSI: '+row['mmsi'].__str__() +'<br>' + 'Group: '+row['group'].__str__() +'<br>''Speed: '+row['speed'].__str__()+' knots',
                'style': {'color' : ''},
                'icon': 'circle',
                'iconstyle':{
                    'fillColor': row['fillColor'],
                    'fillOpacity': 0.8,
                    'radius': 5
                }
            }
        }
        features.append(feature)
        return features

    else:
        vessel_id = row['IMO']

        data = {
               "templates[]": [
                   "modal_validation_errors:0",
                   "modal_email_verificate:0",
                   "r_vessel_types_multi:0",
                   "r_positions_single:0",
                   "vessel_profile:0",
               ],
               "request[0][module]": "ships",
               "request[0][action]": "list",
               "request[0][id]": "0",
               "request[0][data][0][name]": "imo",
               "request[0][data][0][value]": vessel_id,
               "request[0][sort]": "",
               "request[0][limit]": "1",
               "request[0][stamp]": "0",
               "request[1][module]": "top_stat",
               "request[1][action]": "list",
               "request[1][id]": "0",
               "request[1][data]": "",
               "request[1][sort]": "",
               "request[1][limit]": "",
               "request[1][stamp]": "0",
               "dictionary[]": ["countrys:0", "vessel_types:0", "positions:0"],
        }
            
        data = requests.post("https://www.balticshipping.com/", data=data).json()
        try:
            image = data["data"]["request"][0]["ships"][0]["data"]["gallery"][0]["file"]
            headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.3'}
            local_file = open('/Users/Alberto/Desktop/Oscar/UNIVERSIDAD/TFG/test_inicial/out/IMO_photos/' + row['IMO'].__str__() + '.jpg','wb')
            req = Request(url=image, headers=headers)
            with urlopen(req) as response:
                local_file.write(response.read())
        except IndexError:
            image = 'null'
        print(image)
        feature = {
            'type': 'Feature',
            'geometry': {
                'type':'Point',
                'coordinates':[row['lon'],row['lat']]
            },
            'properties': {
                'time': pd.to_datetime(row['date']).__str__(),
                'popup': "<img src=" + image.__str__() + " width = '250' height='200'/>"+'<br>'+'<br>'+'Shipname: '+row['shipname'].__str__() +'<br>'+ 'MMSI: '+row['mmsi'].__str__() +'<br>' + 'Group: '+row['group'].__str__() +'<br>''Speed: '+row['speed'].__str__()+' knots',
                'style': {'color' : ''},
                'icon': 'circle',
                'iconstyle':{
                    'fillColor': row['fillColor'],
                    'fillOpacity': 0.8,
                    'radius': 5
                }
            }
        }
        features.append(feature)
        return features

【问题讨论】:

    标签: python python-3.x loops for-loop


    【解决方案1】:

    它只读取第一行。有什么东西正在停止循环。

    是的,两个返回,因为你的代码是:

    for _, row in s.iterrows():
        if ...:
           ...
           return features
        else:
           ...
           return features
    

    所以在所有情况下,您都会在for 的第一轮返回。

    很可能return features 必须for 之后:

    for _, row in s.iterrows():
        if ...:
           ...
           features.append(feature)
        else:
           ...
           features.append(feature)
    return features
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-05
      • 2019-12-16
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多