列表适合保存多个对象,字典适合描述一个对象。把两者组合起来,就能表达大量真实数据。
products = [
{"name": "键盘", "price": 299, "stock": 10},
{"name": "鼠标", "price": 159, "stock": 5}
]
外层列表表示多个商品,每个字典保存一个商品的完整信息。
一、读取嵌套数据
print(products[0])
print(products[0]["name"])
print(products[1]["price"])
可以从外到内理解:先通过列表索引找到商品,再通过字典键找到具体字段。
二、使用 enumerate 获得编号
之前我们用 range(len(...)) 生成编号:
for index in range(len(products)):
print(index + 1, products[index]["name"])
更常见的写法是 enumerate():
for index, product in enumerate(products, start=1):
print(f"{index}. {product['name']}")
start=1 表示编号从 1 开始。
三、查找数据
def find_product(products, product_name):
for product in products:
if product["name"] == product_name:
return product
return None
找到时返回商品字典,找不到时返回 None。
product = find_product(products, "键盘")
if product is None:
print("没有找到商品")
else:
print(product)
四、筛选数据
找出库存不足的商品:
low_stock_products = []
for product in products:
if product["stock"] < 6:
low_stock_products.append(product)
筛选的基本思路是:遍历全部数据,符合条件的加入新列表。
五、排序数据
按价格从低到高排序:
sorted_products = sorted(
products,
key=lambda product: product["price"]
)
从高到低:
sorted_products = sorted(
products,
key=lambda product: product["price"],
reverse=True
)
这里的 lambda 是一个临时小函数,告诉 sorted() 使用哪个字段排序。现阶段先会使用这个结构即可。
六、统计数据
计算全部库存价值:
total_value = 0
for product in products:
total_value += product["price"] * product["stock"]
print(f"库存总价值:{total_value:.2f}元")
基础练习
- 2. 使用
enumerate() 输出商品编号。
今日项目:库存管理器
products = []
def add_product():
name = input("商品名称:").strip()
price = float(input("商品价格:"))
stock = int(input("库存数量:"))
product = {
"name": name,
"price": price,
"stock": stock
}
products.append(product)
print("商品添加成功")
def show_products():
if len(products) == 0:
print("暂无商品")
return
for index, product in enumerate(products, start=1):
print(
f"{index}. {product['name']} | "
f"{product['price']:.2f}元 | "
f"库存{product['stock']}件"
)
def show_total_value():
total = 0
for product in products:
total += product["price"] * product["stock"]
print(f"库存总价值:{total:.2f}元")
while True:
print("\n1. 添加商品")
print("2. 查看商品")
print("3. 统计库存价值")
print("4. 退出")
choice = input("请选择:").strip()
if choice == "1":
add_product()
elif choice == "2":
show_products()
elif choice == "3":
show_total_value()
elif choice == "4":
break
else:
print("输入无效")
查漏测试
真实项目很少只使用一种知识。今天开始,我们练习的是把多个基础能力组合起来。