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