苦练Python第35天:数据结构挑战题,实战演练

前言

大家好,我是倔强青铜三 。欢迎关注我,微信公众号:倔强青铜三。欢迎点赞、收藏、关注,一键三连!!!

欢迎来到 Python 百日冲刺第 35 天

今天,我们把前面学到的列表、字典、集合、itertoolscollections 全部拉出来遛弯------用一道贴近实战的数据结构小题验收成果。


🎯 任务速览

你拿到一份线上商城的订单列表,每条订单包含:

  • 顾客姓名 customer
  • 商品名称 product
  • 数量 quantity
  • 单价 price

完成 3 个 KPI

  1. 统计 每位顾客累计消费金额
  2. 找出 销量最高的 3 款商品
  3. 公布 单笔价值最大的订单

📦 原始订单数据

python 复制代码
orders = [
    {'customer': 'Alice', 'product': 'Pen', 'quantity': 3, 'price': 5},
    {'customer': 'Bob', 'product': 'Notebook', 'quantity': 2, 'price': 15},
    {'customer': 'Alice', 'product': 'Notebook', 'quantity': 1, 'price': 15},
    {'customer': 'Dave', 'product': 'Pen', 'quantity': 10, 'price': 5},
    {'customer': 'Carol', 'product': 'Pen', 'quantity': 1, 'price': 5},
    {'customer': 'Bob', 'product': 'Pen', 'quantity': 2, 'price': 5},
    {'customer': 'Alice', 'product': 'Pencil', 'quantity': 5, 'price': 2},
]

🛠️ 分步拆解

✅ 1. 每位顾客累计消费

利用 defaultdict(float) 一键累加:

python 复制代码
from collections import defaultdict

customer_totals = defaultdict(float)

for order in orders:
    name = order['customer']
    total = order['quantity'] * order['price']
    customer_totals[name] += total

print("💰 每位顾客累计消费")
for customer, total in customer_totals.items():
    print(f"{customer}: ¥{total}")

✅ 2. 销量 Top 3 商品

Counter 两行搞定:

python 复制代码
from collections import Counter

product_counter = Counter()

for order in orders:
    product_counter[order['product']] += order['quantity']

print("\n📦 销量 Top 3")
for product, qty in product_counter.most_common(3):
    print(f"{product}: {qty} 件")

✅ 3. 单笔最壕订单

max() 搭配 lambda,一眼锁定:

python 复制代码
max_order = max(orders, key=lambda o: o['quantity'] * o['price'])

print("\n💎 单笔最壕订单")
print(max_order)

🔎 运行结果

yaml 复制代码
💰 每位顾客累计消费
Alice: ¥40.0
Bob: ¥40.0
Dave: ¥50.0
Carol: ¥5.0

📦 销量 Top 3
Pen: 16 件
Pencil: 5 件
Notebook: 3 件

💎 单笔最壕订单
{'customer': 'Dave', 'product': 'Pen', 'quantity': 10, 'price': 5}

🧠 知识点复盘

  • defaultdict:按组累加,告别手动判空
  • Counter:统计频次,.most_common() 一键排序
  • max(key=...):自定义排序维度
  • 字典取值 + 列表推导:保持代码简洁

🧪 进阶任务

  • 按消费额给顾客排序并输出排行榜
  • 计算每款商品带来的总收入
  • 找出消费金额超过 ¥40 的 VIP 顾客

最后感谢阅读!欢迎关注我,微信公众号倔强青铜三。欢迎点赞收藏关注,一键三连!!!

相关推荐
WoooChi几秒前
DailyTech-20260902
人工智能·科技·业界资讯
quantdash_cc3 分钟前
批量请求和循环请求有什么区别?从 API 请求次数看量化数据获取的工程设计
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
寻求出路的程序媛5 分钟前
分布式 & 高性能 & 高可用 体系、学习重点、面试点
分布式·后端·面试·性能优化
天远数科8 分钟前
零信任架构实战:基于天远车辆出险记录核验构建自动化信贷网关
运维·人工智能·架构·自动化
weixin_750330239 分钟前
OPC一人公司技术服务商对比:从单体架构到AI Agent协同的演进
大数据·人工智能·架构
腾渊信息科技公司12 分钟前
腾渊科技重磅出品——企业级AI研发落地指南:从编码提效到审查治理的完整方案
人工智能·科技·腾渊科技·腾渊信息科技
geneculture13 分钟前
融智学及其序位逻辑:一项认知本体论的重构纲领——从「物意文三分」到「道零点」的完整公理化体系
人工智能·信息科学·哲学与科学统一性·融智时代(杂志)·序位逻辑·邹晓辉融智学·融智学报
柳叶方舟14 分钟前
Nature:AI 第一次把生物学发现做成“假设—实验—数据分析”闭环?
大数据·论文阅读·人工智能·数据分析·健康医疗
课件帮17 分钟前
教师考编面试模拟授课课件怎么做?课件帮AI生成教案+PPT+数字人试讲
人工智能·面试·powerpoint
RisunJan18 分钟前
项目经理面试知识点梳理
面试·职场和发展·word