You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:如何将SQLite查询结果按Name列拆分为多个对象?

问题描述

我用Python查询SQLite数据库,查询结果已在游标中待提取,简化后代码如下:

connection = sqlite3.connect(IMAGE_LOG_DB_PATH)
connection.isolation_level = None
cur = connection.cursor()
sql_query = "Select date, name, count(*) as sells from sellers group by date, name order by date asc;"
cur.execute(sql_query)
result = cur.fetchall()

查询结果示例:

2023-01-01 | John | 5
2023-01-01 | Mark | 10
2023-01-01 | Alex | 7
2023-01-02 | John | 4
2023-01-02 | Alex | 3
2023-01-03 | John | 3
2023-01-03 | Mark | 4
2023-01-03 | Alex | 3

我需要将这些结果按Name拆分为独立的对象,示例如下:

Object 'John':
2023-01-01 | John | 5
2023-01-02 | John | 4
2023-01-03 | John | 3

Object 'Mark':
2023-01-01 | Mark | 10
2023-01-03 | Mark | 4

Object 'Alex':
2023-01-01 | Alex | 7
2023-01-02 | Alex | 3
2023-01-03 | Alex | 3

我知道可以用循环实现(存在对象则添加条目,不存在则新建),但听说Python有更高效的工具。我了解过ORM,但认为ORM会替换数据库连接/查询且速度更慢,请问实现该需求的合适方法是什么?


解决方案

推荐使用Python标准库中的collections.defaultdict来实现,代码简洁高效,无需额外依赖,也完全兼容你现有的数据库查询逻辑:

from collections import defaultdict

# 用defaultdict创建以卖家名为键、对应记录列表为值的字典
seller_data = defaultdict(list)
for row in result:
    seller_data[row[1]].append(row)

# 按示例格式输出结果
for name, entries in seller_data.items():
    print(f"Object '{name}':")
    for entry in entries:
        print(f"{entry[0]} | {entry[1]} | {entry[2]}")
    print()

为什么选这个方法?

  • 高效:时间复杂度为O(n),和手动循环判断的效率一致,但代码更简洁易读。
  • 轻量:属于Python标准库,无需额外安装依赖,不会像ORM那样改变你的数据库查询流程,也没有额外性能开销。
  • 灵活:后续可直接操作seller_data中的列表,对每个卖家的数据做进一步处理。

如果需要将每个卖家的数据封装成结构化对象(而非列表),可以先定义简单类,再结合defaultdict使用:

from collections import defaultdict

class SellerRecord:
    def __init__(self, date, name, sells):
        self.date = date
        self.name = name
        self.sells = sells

seller_objects = defaultdict(list)
for row in result:
    record = SellerRecord(row[0], row[1], row[2])
    seller_objects[row[1]].append(record)

# 输出结构化对象的结果
for name, records in seller_objects.items():
    print(f"Object '{name}':")
    for rec in records:
        print(f"{rec.date} | {rec.name} | {rec.sells}")
    print()

这种方式既保持了代码简洁性,又能将数据封装为结构化对象,方便后续属性访问和扩展。

内容的提问来源于stack exchange,提问作者sharkyenergy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 09:37:43