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

Python TypeError问题:处理JSON数组字段转为字符串时出现list indices must be integers or slices, not str错误

Python TypeError问题:处理JSON数组字段转为字符串时出现list indices must be integers or slices, not str错误

错误原因分析

你遇到的问题根源很清晰:all_tickets是一个普通Python列表,不是pandas DataFrame,但你试图用字符串键(比如"ticket_cc_emails")来索引它,这就触发了list indices must be integers or slices, not str错误——毕竟列表只能用整数下标访问元素,不能像DataFrame那样用列名字符串做索引。

看你的代码逻辑,你已经把all_tickets转换成了pandas DataFramedf,完全不需要再回到原始列表操作,直接用df处理字段就可以解决问题。

修正后的代码实现

替换你出错的代码块:

# 错误的原代码
combined_cc_emails = [", ".join(sublist) for sublist in all_tickets["ticket_cc_emails"].tolist()]
df_combined = pd.DataFrame({'id': all_tickets['id'], 'combined_cc_emails': combined_cc_emails})

改成下面的写法(直接在已有的df上操作):

# 把ticket_cc_emails列表转成逗号分隔的字符串,空列表自动转为空字符串
df['combined_cc_emails'] = df['ticket_cc_emails'].apply(lambda x: ', '.join(x) if isinstance(x, list) else '')

# 如果确实需要单独提取id和合并后的字段,直接从df中复制即可
df_combined = df[['id', 'combined_cc_emails']].copy()

批量处理多个列表字段(可选优化)

如果你需要处理所有类似的邮件列表字段(比如cc_emails、fwd_emails等),可以用循环批量处理,避免重复写相似代码:

# 定义所有需要转换的列表类型邮件字段
email_list_fields = ['cc_emails', 'fwd_emails', 'reply_cc_emails', 'ticket_cc_emails', 'ticket_bcc_emails']

# 批量生成合并后的字符串字段
for field in email_list_fields:
    # 给新字段加前缀,比如combined_cc_emails
    df[f'combined_{field}'] = df[field].apply(lambda x: ', '.join(x) if isinstance(x, list) else '')

为什么这样能解决问题

  1. df['ticket_cc_emails']是pandas Series,每个元素对应一条票单的ticket_cc_emails列表,支持用apply对每个元素执行自定义逻辑
  2. 用lambda x: ', '.join(x) if isinstance(x, list) else ''可以兼容两种情况:
    • 如果是列表(不管非空还是空),自动用逗号拼接成字符串
    • 如果API返回异常值(不是列表类型),返回空字符串避免报错
  3. 直接在现有df上新增字段,后续保存Parquet/Delta表时会自动包含这些新字段,不需要额外合并DataFrame

验证修正后的流程

修改后,你的代码会正常把列表类型的邮件字段转成逗号分隔的字符串,最终存入Parquet和Delta表,完全符合你把列表转成单字符串的需求。

备注:内容来源于stack exchange,提问作者NutellaKing

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 11:23:04