我正在尝试理解一个Python for循环,它的实现方式如下
samples= [(objectinstance.get('sample', record['token'])['timestamp'], record)
for record in objectinstance.scene]
“scene”是一个包含字典列表的JSON文件,每个字典条目通过令牌的值引用另一个名为“sample”的JSON文件,该文件包含“timestamp”键以及其他键。
虽然我可以大致理解,但我无法解释“record”是如何在这里作为对象的get方法的输出使用的。我认为这是某种列表理解,但不确定。您能帮助理解这一点吗?还能为我提供更好的理解这一点的参考吗?谢谢
2条答案
按热度按时间toiithl61#
在非理解形式中,它如下
objectinstance.get('sample', record['token'])
这看起来像一个方法,它接受两个参数并返回一个json/dictionary{<key1>:<value1>, ... ,'timestmap':<somedata>, ...<keyn>:<valuen>}
并且您正在保存具有此调用的
timestamp
值的记录。如果
objectinstance.get
可以看作因此,正如您所看到的,对象类名称
get
中有一个方法,它接受2个参数,并使用它们进行计算,以在dict/json中提供结果,该结果作为键值timestamp
ndh0cuux2#
是的,你是对的,它是一个列表理解,从图式上看,它是这样的:
结果将是一个touple列表,其中
(objectinstance.get('sample', record['token'])['timestamp']
是第一个条目,record
是第二个条目。此外,
objectinstance.get('key', default)
从一个dict中获取'key'
,如果不存在,则返回default
值,请参阅python.org上的文档。get方法的结果似乎也是一个dict,从中检索关键字['timestamp']
的值。