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

Python 2D列表匹配索引列求和:按user_ID分组统计onDuration并修复报错

报错原因

你当前报错是因为userIDs列表里存储的都是单独的整数类型user_ID值,你在循环中使用了ids[0]对整数做下标取值操作,直接触发了类型错误。另外你的整体实现逻辑冗余且存在问题,无需嵌套循环遍历两个列表做匹配,有更简洁高效的实现方式。

方案1:直接在SQL查询中完成分组求和(最推荐)

求和聚合本身就是SQL的原生能力,直接修改查询语句就能得到你要的结果,不需要额外写Python逻辑处理:

SELECT user_ID, SUM(onDuration) FROM onRecord GROUP BY user_ID

执行这条语句后fetchall得到的结果直接就是你要的分组求和后的列表,连后续处理都省了。

注意:如果你的onDuration字段是时间格式而非秒数整数,需要根据你用的数据库类型调整时间求和的函数,比如MySQL用SEC_TO_TIME(SUM(TIME_TO_SEC(onDuration)))就能直接得到时分秒格式的求和结果。

方案2:用Pandas完成分组求和

如果你已经把数据读到了df里,直接用pandas的groupby方法就行,完全不需要自己写循环:

import pandas as pd

# 先把onDuration列转成 timedelta 类型方便时间求和
df['onDuration'] = pd.to_timedelta(df['onDuration'])
# 按user_ID分组求和
res_df = df.groupby('user_ID', as_index=False)['onDuration'].sum()
# 转成你要的嵌套列表格式
calcResult = res_df.values.tolist()

方案3:原生Python实现(不用pandas)

如果不想引入pandas,用字典做分组统计就行:

result = c.execute("SELECT user_ID, onDuration FROM onRecord").fetchall()
c.close()

from collections import defaultdict
import datetime

sum_dict = defaultdict(datetime.timedelta)
for user_id, duration_str in result:
    # 把时分秒字符串转成timedelta求和
    h, m, s = map(int, duration_str.split(':'))
    sum_dict[user_id] += datetime.timedelta(hours=h, minutes=m, seconds=s)

# 转成你要的格式
calcResult = []
for user_id, total in sum_dict.items():
    # 把timedelta转回时分秒字符串
    total_sec = int(total.total_seconds())
    h = total_sec // 3600
    m = (total_sec % 3600) // 60
    s = total_sec % 60
    duration_str = f"{h:02d}:{m:02d}:{s:02d}"
    calcResult.append([user_id, duration_str])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 19:15:09