【问题标题】:When using os.stat, is a meta variable created?使用 os.stat 时,是否创建了元变量?
【发布时间】:2015-07-07 19:19:03
【问题描述】:

我目前正在使用本指南学习 python(如果您需要更多上下文)http://www.diveintopython3.net/comprehensions.html#dictionarycomprehension

>>> import os, glob, humansize
>>> metadata_dict = {f:os.stat(f) for f in glob.glob('*')}                                  ①
>>> humansize_dict = {os.path.splitext(f)[0]:humansize.approximate_size(meta.st_size) \     
...                   for f, meta in metadata_dict.items() if meta.st_size > 6000}          ②
>>> list(humansize_dict.keys())                                                             ③
['romantest9', 'romantest8', 'romantest7', 'romantest6', 'romantest10', 'pluraltest6']
>>> humansize_dict['romantest9']                                                            ④
'6.5 KiB'

为什么是 'humansize.approximate_size(meta.st_size)' 以及 'for f, meta' 中的元变量是从哪里来的?

【问题讨论】:

  • 您正在循环遍历meta_dict.items(),因此meta 是键值对中的值(f 是键)。不知道humansize.approximate_size() 是从哪里来的,那将来自进口。 meta_dict 是您使用形成值的 os.stat(f) 表达式创建的字典,因此 meta 引用之前返回的任何 os.stat(f)
  • metadata_dict.items()metadata_dict 字典中返回一个元组或一对(key, value)f 是键,meta 是值

标签: python python-3.x dictionary-comprehension


【解决方案1】:

这与os.stat无关。

你似乎跳过了那章的主题,理解——这是一个字典理解。与前面对列表推导的讨论一样,dict comp 为它迭代的 dict 中的每个项目创建变量。这段代码的脚注中对此进行了解释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-13
    • 2020-12-19
    • 2020-04-07
    • 2016-05-29
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    相关资源
    最近更新 更多