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

Python3 matplotlib不支持生成器作为输入的绘图报错修复

报错根因

该报错由Python 2与Python 3的map()函数返回值差异导致:

  • Python 2中map()执行后直接返回列表类型,可直接传入matplotlib绘图接口
  • Python 3中map()返回惰性生成器对象,matplotlib不支持直接接收生成器作为绘图输入参数,因此触发RuntimeError: matplotlib does not support generators as input错误。
适配方案

两种修改方式都可以解决问题,按需选择即可:

方案1:最小改动适配

找到plot_tour、plot_lines函数中所有传入plt.plot()的map()调用,在外层包裹list()做显式类型转换即可。
原Python 2示例代码写法:

plt.plot(
    map(lambda point: point[0], tour_points),
    map(lambda point: point[1], tour_points),
    line_color, marker=point_marker
)

修改后Python 3兼容写法:

plt.plot(
    list(map(lambda point: point[0], tour_points)),
    list(map(lambda point: point[1], tour_points)),
    line_color, marker=point_marker
)

方案2:替换为列表推导式(推荐)

直接将map()写法替换为Python 3生态更常用的列表推导式,可读性更高,无需额外类型转换:

# 提前提取横纵坐标列表
x = [p[0] for p in tour_points]
y = [p[1] for p in tour_points]
plt.plot(x, y, line_color, marker=point_marker)

修改完成后重新运行绘图相关函数即可正常输出TSP路径可视化结果,同类旧Python 2代码迁移到Python 3时遇到的同类matplotlib入参报错,都可以通过上述两种方式修复。

内容的提问来源于stack exchange,提问作者John Denn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 18:16:01