微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

有人可以向我解释 xs 值 "xs = [48, 117, 200, 240, 160, 260, 220]" 是如何转移到 "height" 的吗? Python

如何解决有人可以向我解释 xs 值 "xs = [48, 117, 200, 240, 160, 260, 220]" 是如何转移到 "height" 的吗? Python

我想了解 xs 值 "xs = [48,117,200,240,160,260,220]" 是如何转换为 "height" 的。为什么我们有“maxheight”而不是“height”作为我们的变量?我不明白代码这一特定部分的逻辑。谢谢。

import turtle

def drawBar(t,height):
    """ Get turtle t to draw one bar,of height. """
    t.begin_fill()               # start filling this shape
    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)
    t.end_fill()                 # stop filling this shape



xs = [48,220]  # here is the data
maxheight = max(xs)
numbars = len(xs)
border = 10

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

tess = turtle.Turtle()           # create tess and set some attributes
tess.color("blue")
tess.pensize(3)



for a in xs:
    if a < 100:
        tess.fillcolor("green")
    elif 100 <= a < 200:
        tess.fillcolor("yellow")
    else:
        tess.fillcolor("red")
    drawBar(tess,a)

wn.exitonclick()

enter image description here

解决方法

我建议你玩代码。如果您不明白为什么将“maxheight”用作变量而不是“height”,请将“maxheight”变量更改为“height”,看看会发生什么。不要担心你不会破坏你的电脑。只需运行新代码。

然后查看代码并记住变量可以命名为python规则内的任何名称。 Maxheight 可以被命名为狗猫或兔子。高度这个词也可以是任何字母 a、B 或 C。看看程序员把“高度”这个词放在哪里。 “问你自己是 height 函数 drawbar 中参数的名称吗?然后看看代码行 maxheight = max(xs)。

这是一个变量吗?程序员是否将名称 maxheight 分配给内置于函数 max 中的 python?在这种情况下,函数 max 使用列表 xs 的一个参数。从这一点开始,每次调用 maxheight 时,代码都会运行列表 xs 上的内置函数 max。

我虚心建议你做两件事来彻底理解这部分代码。谷歌和审查变量,然后在 python 中函数和参数。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。