开始使用免费开始使用

子集拿下

对 Python 列表取子集非常简单。看下面的代码示例,先创建列表 x,然后从中选出 "b"。请记住这是第二个元素,所以索引是 1。也可以使用负索引。

x = ["a", "b", "c", "d"]
x[1]
x[-3] # same result!

还记得之前的 areas 列表吗?它同时包含字符串和浮点数。它的定义已经在脚本里了。您能补上正确的代码来完成一些 Python 子集操作吗?

本练习是课程的一部分

Python 入门

查看课程

练习说明

  • 打印出 areas 列表的第二个元素(其值为 11.25)。
  • 取出并打印 areas 的最后一个元素,即 9.50。这里使用负索引更合适!
  • 选择表示客厅面积的数字(20.0)并将其打印出来。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Create the areas list
areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50]

# Print out second element from areas
print(areas[____])

# Print out last element from areas
print(areas[____])

# Print out the area of the living room
print(areas[____])
编辑并运行代码