在嵌套对象中获取总和

Posted

技术标签:

【中文标题】在嵌套对象中获取总和【英文标题】:Getting a total sum in a nested object 【发布时间】:2021-05-15 11:29:19 【问题描述】:
with jsonlines.open('myfile.jsonl') as readfile:
    for contents in readfile:
        print (len(contents['tokens']))
  

所以,我有一个 jsonl 文件,其中每一行都是一个包含列表、字典、字符串和整数的字典。我想遍历每行列表的 len() 并获得总长度。所以这里的代码给了我: 4 11 7 12 9 7 14 9 10 10 4 8

但是当我尝试 sum() 或 count() 或任何我得到的东西时,我想要一个总数,abd

TypeError: 'int' 对象不可迭代

每个 jsonl 行看起来像这样,所以你可以看到它非常嵌套。我想计算每一行上每个“令牌”键的 len() 并将它们加在一起。

“text”:”full text...”,"","_input_hash":-随机数,"_task_hash":-随机数,"tokens":["text":"word ","start":number,"end":number,"id":number,"ws":true or false,"text":"word","start":number,"end":number, "id"number,"ws":true or false...],"_session_id":"dataset name-annotator name","_view_id":"ner_manual","spans":["start":number, "end":number,"token_start":number,"token_end":number,"label":"POS 标签","answer":"accept"

【问题讨论】:

请显示您的引发错误的代码以及输入 json 的相关 sn-p 【参考方案1】:

你可以简单地累加长度:

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)

【讨论】:

【参考方案2】:

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

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

【讨论】:

以上是关于在嵌套对象中获取总和的主要内容,如果未能解决你的问题,请参考以下文章