You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python的Folium地图中打印for循环的索引值?

在Folium图标旁动态显示循环索引值

我编写了一段Python代码,想要在Folium图标旁显示数字,要求这些数字是for循环的索引值(动态生成),但目前的写法无法正确渲染出索引。

原尝试代码:

for point in range(0, len(coordinates_st)):
    # 显示数字
    folium.Marker(location=[72.89, -124.59+2], icon=DivIcon(
        icon_size=(150, 36),
        icon_anchor=(7, 20),
        html='<div style="font-size: 18pt;">r{point}</div>',
    )).add_to(map_st)

我希望在图标旁显示循环的索引(比如1、2...),而非以下代码中的固定值:

for point in range(0, len(coordinates_st)):
    # 显示数字
    folium.Marker(location=[72.89, -124.59+2], icon=DivIcon(
        icon_size=(150, 36),
        icon_anchor=(7, 20),
        html='<div style="font-size: 18pt;">1, 2</div>',
    )).add_to(map_st)

当前效果:
当前Folium地图


解决方法

问题核心是HTML字符串没有正确插入循环变量,用Python字符串格式化语法即可解决:

方法1:f-string(Python 3.6+推荐)

在字符串前加f,直接用{变量名}引用循环索引,若要从1开始计数则用point + 1:

for point in range(0, len(coordinates_st)):
    folium.Marker(
        location=[72.89, -124.59 + 2],
        icon=DivIcon(
            icon_size=(150, 36),
            icon_anchor=(7, 20),
            html=f'<div style="font-size: 18pt;">{point + 1}</div>'
        )
    ).add_to(map_st)

方法2:str.format()(兼容低版本Python)

用format()方法传入索引值:

for point in range(0, len(coordinates_st)):
    folium.Marker(
        location=[72.89, -124.59 + 2],
        icon=DivIcon(
            icon_size=(150, 36),
            icon_anchor=(7, 20),
            html='<div style="font-size: 18pt;">{}</div>'.format(point + 1)
        )
    ).add_to(map_st)

注意事项

  • 若需要从0开始显示索引,直接使用{point}即可,无需加1。
  • 调整icon_anchor的坐标值,可以微调数字相对于图标的位置,确保显示在目标位置(比如HOME图标旁)。

内容的提问来源于stack exchange,提问作者Tanmoy Das

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 21:15:32