串列切片與分割
從串列裡提取單個元素只是基本操作,你還可以對串列進行「切片」,也就是一次性從串列中選擇多個元素。語法格式如下:
my_list[start:end]
start 索引包含在內,而 end 索引不包含在內。不過,這兩個索引其實都可以省略。如果你不指定 start 索引,Python 會明白你是想從串列的開頭開始切片。
本練習屬於課程
Python 入門
練習說明
- 使用切片建立一個串列
downstairs,其中包含areas的前 6 個元素。 - 建立
upstairs,用於存放areas的後4個元素。這次記得省略end索引來簡化切片語法。 - 使用
print()印出downstairs和upstairs。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create the areas list
areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50]
# Use slicing to create downstairs
downstairs = areas[____]
# Use slicing to create upstairs
upstairs = areas[____]
# Print out downstairs and upstairs
____
____