用巢狀列表整理股票資料
列表也可以包含其他列表。以下例子中,x 是一個由三個列表組成的「巢狀列表」:
x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
你可以用索引在巢狀列表中擷取內層的列表。若要取出 x 中的第一個列表,可以使用以下指令:
x[0]
[1, 2, 3]
你先前建立的兩個列表 names 和 prices 已可在你的工作環境中使用。
本練習屬於課程
Python 金融入門
練習說明
- 建立一個名為
stocks的列表,內容依序包含names和prices這兩個列表。 - 使用列表索引,從
stocks中擷取prices(記得prices是stocks的第二個元素)。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create and print the nested list stocks
stocks = [____, ____]
print(stocks)
# Use list indexing to obtain the list of prices
print(stocks[____])