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

Python如何按id统计字典列表中text、text_2字段的元素数与单词总数

Python实现方案

直接遍历列表中的每个字典元素分别统计即可,默认按空格拆分单词,即可匹配你要求的计数规则,可直接运行的代码如下:

def process_data(origin_list):
    res = []
    for item in origin_list:
        # 统计text字段:元素个数+总单词数
        text_len = len(item['text'])
        text_word_sum = sum(len(s.split()) for s in item['text'])
        # 统计text_2字段:元素个数+元组第三位文本的总单词数
        text2_len = len(item['text_2'])
        text2_word_sum = sum(len(t[2].split()) for t in item['text_2'])
        # 组装结果
        res.append({
            'id': item['id'],
            'text': (text_len, text_word_sum),
            'text_2': (text2_len, text2_word_sum)
        })
    return res

# 测试调用
myList = [
    {
        'id':1,
        'text':[
            'I like cheese.', 
            'I love cheese.',
            'oh!'
        ],
        'text_2': [
            ('david', 'david', 'I do not like cheese.'),
            ('david', 'david', 'cheese is good.')
        ]
    },
    {
        'id':2,
        'text':[
            'I like strawberry.',
            'I love strawberry'
        ],
        'text_2':[
            ('alice', 'alice', 'strawberry is good.'),
            ('alice', 'alice', ' strawberry is so so.')
        ]
    }
]
output = process_data(myList)
print(output)

输出结果

运行后得到的结果和你给出的理想输出完全一致:

[
    {'id': 1, 'text': (3, 7), 'text_2': (2, 8)},
    {'id': 2, 'text': (2, 6), 'text_2': (2, 7)}
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:48:01