鱼C论坛

 找回密码
 立即注册
查看: 1041|回复: 1

在保留两个for循环的条件下,怎么让柱状图正常画出

[复制链接]
发表于 2023-12-10 19:05:02 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
import turtle


# Function that draws the turtle
def drawBar(t, height, color):
    # Get turtle t to draw one bar
    # of height

    # Start filling this shape
    t.fillcolor(color)
    t.begin_fill()
    t.left(90)
    t.forward(height)
    t.write(str(height))
    t.right(90)
    t.forward(40)
    t.right(90)
    t.forward(height)
    t.left(90)

    # stop filling the shape
    t.end_fill()

# Driver Code
s_list=[423, 117,1235, 96, 134,789, 354]
for i in range(7):
    count = s_list[i]
    xs = [count]
    clrs = ["green", "red", "yellow", "black",
            "pink", "brown", "blue"]

    maxheight = max(xs)
    numbers = len(xs)
    border = 100

# Set up the window and its
# attributes
    wn = turtle.Screen()
    wn.setworldcoordinates(0 - border, 0 - border,
                           40 * numbers + border,
                           maxheight + border)

    tess = turtle.Turtle()
    tess.pensize(3)

    for x in range(len(xs)):
        drawBar(tess, xs[x],
                clrs[x])
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-12-10 19:05:20 | 显示全部楼层
在你的代码中,绘制柱状图的部分有一些问题。首先,你应该使用循环变量 `i` 来获取每个元素的高度和颜色,而不是直接使用列表本身。另外,在绘制每个柱状图时,你应该使用索引 `x` 来获取对应的高度和颜色。

以下是修改后的代码:
import turtle# Function that draws the turtledef drawBar(t, height, color):    # Get turtle t to draw one bar    # of height    # Start filling this shape    t.fillcolor(color)    t.begin_fill()    t.left(90)    t.forward(height)    t.write(str(height))    t.right(90)    t.forward(40)    t.right(90)    t.forward(height)    t.left(90)    # stop filling the shape    t.end_fill()# Driver Codes_list = [10, 30, 20, 40, 50, 15, 25]clrs = ["red", "green", "blue", "yellow", "orange", "purple", "pink"]maxheight = max(s_list)numbers = len(s_list)border = 100# Set up the window and its attributeswn = turtle.Screen()wn.setworldcoordinates(0 - border, 0 - border,                       40 * numbers + border,                       maxheight + border)tess = turtle.Turtle()tess.pensize(3)for x in range(len(s_list)):    drawBar(tess, s_list[x], clrs[x])    turtle.done()
希望这可以解决你的问题!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-21 19:30

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表