读取JSON文件的Python for循环

4smxwvx5  于 2022-11-19  发布在  Python
关注(0)|答案(2)|浏览(252)

我正在尝试理解一个Python for循环,它的实现方式如下

samples= [(objectinstance.get('sample', record['token'])['timestamp'], record) 
            for record in objectinstance.scene]

“scene”是一个包含字典列表的JSON文件,每个字典条目通过令牌的值引用另一个名为“sample”的JSON文件,该文件包含“timestamp”键以及其他键。
虽然我可以大致理解,但我无法解释“record”是如何在这里作为对象的get方法的输出使用的。我认为这是某种列表理解,但不确定。您能帮助理解这一点吗?还能为我提供更好的理解这一点的参考吗?谢谢

toiithl6

toiithl61#

在非理解形式中,它如下

samples = []
for record in objectinstance.scene:
    data = (
              objectinstance.get('sample', record['token'])['timestamp'],
              record
           )
    samples.append(data)

objectinstance.get('sample', record['token'])这看起来像一个方法,它接受两个参数并返回一个json/dictionary
{<key1>:<value1>, ... ,'timestmap':<somedata>, ...<keyn>:<valuen>}
并且您正在保存具有此调用的timestamp值的记录。
如果objectinstance.get可以看作

class Tmp:
    def __init__(self):
        self.scene = [{'token': 'a'}, {'token':'b'}, {'token':'c'}] 
    def get(self, arg1, arg2):
         # calculation
         
         return result 
     
objectinstance = Tmp()

samples =[]

for record in objectinstance.scene:
    object_instance_data = objectinstance.get('sample', record['token'])
    data = object_instance_data['timestamp']
    samples.append(data)

因此,正如您所看到的,对象类名称get中有一个方法,它接受2个参数,并使用它们进行计算,以在dict/json中提供结果,该结果作为键值timestamp

ndh0cuux

ndh0cuux2#

是的,你是对的,它是一个列表理解,从图式上看,它是这样的:

samples = [(timestamp, item) for item in list_of_dicts]

结果将是一个touple列表,其中(objectinstance.get('sample', record['token'])['timestamp']是第一个条目,record是第二个条目。
此外,objectinstance.get('key', default)从一个dict中获取'key',如果不存在,则返回default值,请参阅python.org上的文档。get方法的结果似乎也是一个dict,从中检索关键字['timestamp']的值。

相关问题