子集和切片
对 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[____])