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

Python turtle如何连接列表点与后第9个点并解决下标越界问题

解决Python turtle点连线下标越界问题

问题根源

你当前代码的报错是因为当索引i超过31时,i+9的结果大于等于40,而你的点列表总长度为40,有效下标范围是0~39,直接访问i+9就会触发下标越界错误。你需要实现的“超过列表长度就回到开头继续计数”的逻辑,刚好可以用取余运算符%实现。

取余运算符%的用法

%的作用是返回两个数相除的余数,我们可以将目标索引对列表总长度取余,自动实现超出后回绕的效果:

  • 当i+9 < 40时,(i+9) % 40的结果就是i+9本身,和原有逻辑一致
  • 当i+9 >=40时,余数就是回绕后的下标,比如i=31时,(31+9)%40=40%40=0,刚好对应你要的下标0的点

你只需要将代码里goto(pointList[i + 9])替换为goto(pointList[(i + 9) % len(pointList)])即可解决越界问题。

另外你提供的坐标文件里存在空行,原有代码读取时会触发报错,建议读取行时增加空行判断。同时你写的循环里额外声明i变量是冗余的,可以直接用循环变量遍历下标。

修改后的完整代码

from turtle import *

speed(10)
fileName = input("What is the name of the file? ")
file = open(fileName, 'r', encoding='UTF-8')

pointList = []
penup()

for line in file:
    # 跳过空行
    line = line.strip()
    if not line:
        continue
    lineTokens = line.split()
    x = float(lineTokens[0])
    y = float(lineTokens[1])
    point = (x,y)
    pointList.append(point)
# 关闭文件避免资源泄漏
file.close()

def drawPoints():
    for point in pointList:
        goto(point)
        dot(5, "black")
        
drawPoints()

n = len(pointList)
pencolor("red")
for i in range(n):
    goto(pointList[i])
    down()
    # 用%实现下标回绕
    goto(pointList[(i + 9) % n])
    up()

# 绘制完成后保持窗口不自动关闭
done()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 22:15:05