【问题标题】:Assigning value of element to the variable output将元素的值分配给变量输出
【发布时间】:2021-12-27 20:39:16
【问题描述】:

所以,我在 coursera 上的初学者 Python 课程,有一个问题我就是不明白:

lst的第34个元素的值赋给变量output

这里是列表:

1st = ["hi", "morning", "dog", "506", "caterpillar", "balloons", 106, "yo-yo", "python",
       "moon", "water", "sleepy", "daffy", 45, "donald", "whiteboard", "glasses",
       "markers", "couches", "butterfly", "100", "magazine", "door", "picture", "window",
       ["Olympics", "handle"], "chair", "pages", "readings", "burger", "juggle", "craft",
       ["store", "poster", "board"], "laptop", "computer", "plates", "hotdog", "salad",
       "backpack", "zipper", "ring", "watch", "finger", "bags", "boxes", "pods", "peas",
       "apples", "horse", "guinea pig", "bowl", "EECS"]

我该怎么处理这件事?我不是在寻找任何人直接给我答案,而是帮助我了解这个问题想要从我这里得到什么以及如何解决它。

【问题讨论】:

  • 问题是要求您将lst 的第34 个元素(lst[33],因为列表是0 索引)分配给一个名为output 的变量(=)。这就是output = lst[33]

标签: python list variables output element


【解决方案1】:
output = 1st[34]

“这就是它所说的,通过索引列表,您可以获得值并将其分配给变量输出”

【讨论】:

    【解决方案2】:

    列表的索引从 0 开始。
    因此,要访问列表中的第 34 个元素,需要输入索引33
    代码应该是这样的:

    1st = ["hi", "morning", "dog", "506", "caterpillar", "balloons", 106, "yo-yo", "python",
           "moon", "water", "sleepy", "daffy", 45, "donald", "whiteboard", "glasses",
           "markers", "couches", "butterfly", "100", "magazine", "door", "picture", "window",
           ["Olympics", "handle"], "chair", "pages", "readings", "burger", "juggle", "craft",
           ["store", "poster", "board"], "laptop", "computer", "plates", "hotdog", "salad",
           "backpack", "zipper", "ring", "watch", "finger", "bags", "boxes", "pods", "peas",
           "apples", "horse", "guinea pig", "bowl", "EECS"];
    output = lst[33];
    

    【讨论】:

      【解决方案3】:

      要索引一个列表,正确的语法是:

      list[i] 其中i 是您要检索的元素的索引。所以在你的情况下:

      output = 1st[34]

      祝 Corsera 好运!

      【讨论】:

        【解决方案4】:

        是的。我最终自己弄清楚了。不过还是非常感谢你们俩。

        是的,我这样做了(以防其他人也遇到类似的问题):

        你需要找到索引 34,因为 python 是 0 索引

        输出将是“笔记本电脑”

        print(lst[34])
        

        现在您需要将值“laptop”(第 35 个元素)分配给变量“output”

        看起来像:

        output = "laptop"
        print(output)
        

        【讨论】:

        • 尝试使用更好的标题和副标题来格式化答案,对于您认为重要的每一行都使用 H1 或 #(可能的最大标题)不是一个好习惯。
        猜你喜欢
        • 2018-08-04
        • 1970-01-01
        • 2012-01-05
        • 1970-01-01
        • 2012-12-12
        • 1970-01-01
        • 1970-01-01
        • 2017-09-28
        相关资源
        最近更新 更多