黄同学的后端和 Agent 笔记开通
Hello 后端

动手做:统计每个用户的订单

黄同学约 4 分钟读完免费

读一份订单清单,每行是一笔订单:用户 id、商品 id、数量、单价(分)。算出每个用户一共花了多少钱、买过几种商品,按用户 id 从小到大打印出来。

做完,这一节的变量、类型转换、if、for、字符串的 strip 和 split、字典、集合,你都用过一遍了。

要先学过:

步骤

  1. 在家目录的 hb-python 目录(跑起第一个 Python 程序建的)里,建一个 syntax 目录,走进去:

    bash
    cd ~/hb-python
    mkdir syntax
    cd syntax

    hb-python 里钉了 Python 3.14,在它下面的目录里 uv run,uv 会往上找到那个 .python-version,用的也是 3.14。

    在 syntax 里新建 orders.txt,内容照抄。第一行是表头,中间有两行是空的,那是故意留的:

    text
    user_id,product_id,quantity,price
    3,101,1,1990
    1,205,2,500
    2,101,1,1990
    1,101,1,1990
    
    5,330,3,1200
    2,412,1,8800
    3,205,4,500
    1,205,1,500
    4,101,2,1990
    5,101,1,1990
    2,330,2,1200
    
    3,412,1,8800
    1,330,1,1200
    4,205,10,500
    5,330,1,1200
    2,101,1,1990
    3,101,2,1990
    1,412,1,8800
    4,330,1,1200
  2. 在同一个目录里新建 stats.py,先把文件一行行打出来看看:

    python
    with open("orders.txt", encoding="utf-8") as f:
        for line in f:
            print(line)

    头两行先照抄。with open(...) as f 打开文件,交给名字 f;for line in f 每次从文件里读一行,贴上名字 line。它们在文件和 JSON 细讲,这里只要知道 line 是一个字符串就够了。

    bash
    uv run stats.py
    text
    user_id,product_id,quantity,price
    
    3,101,1,1990
    
    1,205,2,500
    
    ...

    每行下面都多了一行空的。因为读出来的每一行,末尾都带着一个换行符,print 打印完又换一次行。

  3. 把 print(line) 换掉:先用 strip() 去掉末尾的换行符,再跳过表头和空行,最后用 split(",") 切开:

    python
    with open("orders.txt", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line == "" or line.startswith("user_id"):
                continue
            parts = line.split(",")
            print(parts)
    text
    ['3', '101', '1', '1990']
    ['1', '205', '2', '500']
    ['2', '101', '1', '1990']
    ...

    一共 19 行,表头和两行空行都没了。留意列表里的每一项都带着引号:它们还是字符串,不能直接拿来乘。

  4. 现在轮到你写了。把 print(parts) 换成你的代码,要做到:

    • 用 int() 把四项转成整数。
    • 在循环外面准备一个字典 totals,按用户 id 累加金额:每笔订单的金额是数量 × 单价。
    • 再准备一个字典 products,键是用户 id,值是一个集合,装这个用户买过的商品 id。同一种商品买两次,集合里只留一个。
    • 循环结束后,按用户 id 从小到大,每个用户打印一行:用户 id、总金额、买过几种商品,中间用一个空格隔开。

    提示:累加用 totals.get(user_id, 0),字典和集合的「遍历字典」一节有一样的写法。一个用户第一次出现时,products 里还没有他,先放一个 set() 进去。排序用 sorted(totals),它交出排好序的键。

  5. 运行:

    bash
    uv run stats.py

    应该看到:

    text
    1 13490 4
    2 15180 3
    3 16770 3
    4 10180 3
    5 6790 2

    第一行:用户 1 一共花了 13490 分,买过 4 种商品。

    答案(点开看)
    python
    totals = {}
    products = {}
    
    with open("orders.txt", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line == "" or line.startswith("user_id"):
                continue
            parts = line.split(",")
            user_id = int(parts[0])
            product_id = int(parts[1])
            quantity = int(parts[2])
            price = int(parts[3])
    
            totals[user_id] = totals.get(user_id, 0) + quantity * price
            if user_id not in products:
                products[user_id] = set()
            products[user_id].add(product_id)
    
    for user_id in sorted(totals):
        print(user_id, totals[user_id], len(products[user_id]))

    四行 int(parts[...]) 也可以用解包写成一行:user_id, product_id, quantity, price = parts,再分别转成整数。products 也可以用 defaultdict(set),就不用判断第一次出现了。

  6. 自己验一下:用户 1 的订单在清单里有 5 行,挑出来手算一遍。205 买了两次,种数还是算 1 种吗?

做完了

第 5 步的输出和上面的 5 行一模一样,就做完了。对不上时:

  • 报 ValueError: invalid literal for int() with base 10: 'user_id':表头没跳过。看 startswith 那一行写对没有。
  • 报 ValueError: invalid literal for int() with base 10: '':空行没跳过,或者 strip() 写在了判断空行的后面。
  • 报 KeyError:某个用户第一次出现时,直接 totals[user_id] + ... 了。改用 get。
  • 金额对,种数偏大:products 里放的是列表,不是集合,重复的商品被算了两次。
  • 顺序不对:打印时没有 sorted。

orders.txt 和 stats.py 留着也行,删掉也行,后面的动手做页用不到它们。