掘金 人工智能 07月26日 10:15
苦练Python第35天:数据结构挑战题,实战演练
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

本文通过一道贴近实战的订单分析小题,回顾并运用了Python中的列表、字典、集合、itertools和collections等数据结构。文章详细演示了如何利用collections.defaultdict统计每位顾客的累计消费金额,使用collections.Counter找出销量最高的三款商品,并通过max()函数结合lambda表达式定位单笔价值最大的订单。最后,对涉及的知识点如defaultdict的按组累加、Counter的频次统计和max()函数的自定义排序维度进行了复盘,并给出了进阶的练习方向,旨在帮助读者巩固Python数据结构的应用能力。

🎯 **统计顾客累计消费**:利用`collections.defaultdict(float)`可以方便地为每位顾客按订单累加消费总额,无需手动检查字典中是否存在键,简化了代码逻辑。

📦 **找出销量TOP3商品**:`collections.Counter`是处理计数类问题的利器,通过遍历订单数据,统计每种商品的销售数量,再调用`.most_common(3)`即可轻松获取销量最高的三款商品及其数量。

💎 **定位最大价值订单**:使用内置的`max()`函数,并结合`lambda`表达式定义排序依据(订单数量乘以单价),能够高效地从订单列表中找出单笔消费金额最高的订单。

🧠 **核心知识点提炼**:文章强调了`defaultdict`用于分组累加、`Counter`用于频次统计和排序、以及`max(key=...)`用于自定义排序维度的实用性,这些都是Python数据结构处理实际问题的关键技巧。

前言

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

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

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


🎯 任务速览

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

完成 3 个 KPI

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

📦 原始订单数据

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) 一键累加:

from collections import defaultdictcustomer_totals = defaultdict(float)for order in orders:    name = order['customer']    total = order['quantity'] * order['price']    customer_totals[name] += totalprint("💰 每位顾客累计消费")for customer, total in customer_totals.items():    print(f"{customer}: ¥{total}")

✅ 2. 销量 Top 3 商品

Counter 两行搞定:

from collections import Counterproduct_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,一眼锁定:

max_order = max(orders, key=lambda o: o['quantity'] * o['price'])print("\n💎 单笔最壕订单")print(max_order)

🔎 运行结果

💰 每位顾客累计消费Alice: ¥40.0Bob: ¥40.0Dave: ¥50.0Carol: ¥5.0📦 销量 Top 3Pen: 16 Pencil: 5 Notebook: 3 💎 单笔最壕订单{'customer': 'Dave', 'product': 'Pen', 'quantity': 10, 'price': 5}

🧠 知识点复盘


🧪 进阶任务


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

Fish AI Reader

Fish AI Reader

AI辅助创作,多种专业模板,深度分析,高质量内容生成。从观点提取到深度思考,FishAI为您提供全方位的创作支持。新版本引入自定义参数,让您的创作更加个性化和精准。

FishAI

FishAI

鱼阅,AI 时代的下一个智能信息助手,助你摆脱信息焦虑

联系邮箱 441953276@qq.com

相关标签

Python 数据结构 collections 订单分析 编程实战
相关文章