获取嵌套对象中的总和

2024-03-29 14:55:30 发布

您现在位置:Python中文网/ 问答频道 /正文

with jsonlines.open('myfile.jsonl') as readfile:
    for contents in readfile:
        print (len(contents['tokens']))
  

因此,我有一个jsonl文件,其中每一行都是一个包含列表、字典、字符串和整数的字典。我想在每一行上循环遍历列表的len(),得到总长度。这里的代码告诉我: 四, 11 7. 12 9 7. 14 9 10 10 4. 8

但当我尝试求和()或计数()或任何我得到的结果时,我想要一个总数

TypeError: 'int' object is not iterable

每个jsonl行看起来都像这样,所以您可以看到它非常嵌套。我想计算每行上每个“tokens”键的len(),并将它们全部相加

{text]:“全文…”,“{u-input\u-hash”:-随机数,“{u-task\u-hash”:-随机数,“{text]:“word”,“start”:number”,“id”:number,“ws”:true或false},{text:“word”,“start”:number,“end”:number,“id”number,“ws:“true或false”},“{u-session id:“数据集名称注释器名称”,“{u-view\u-id:“ner\u-manual”,“span:“{start:“{:number,“end”:number,“token\u start”:number,“token\u end”:number,“label”:“POS tag”},“answer”:“accept”}


2条回答

您可以简单地累积长度:

with jsonlines.open('myfile.jsonl') as readfile:
    total = 0
    for contents in readfile:
        total += len(contents['tokens'])
    print(total)

或者在适当的生成器表达式上使用sum

with jsonlines.open('myfile.jsonl') as readfile:
    total = sum(len(contents['tokens']) for contents in readfile)
    print(total)

pythonic解决方案是使用生成器表达式,即可由函数使用的for循环:

with jsonlines.open('myfile.jsonl') as readfile:
    total_tokens = sum(len(contents['tokens']) for contents in readfile)
    print(total_tokens)

相关问题 更多 >