用嵌套列表整理股票数据
列表也可以包含其他列表。如下例所示,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[____])