以上列表中的迭代过程如何工作?

时间:2019-07-18 19:04:47

标签: python list-comprehension

sum((float(d['cty']) for d in mpg)) / len(mpg)

输出:16.86

当我们处理列表并获取与之对应的值时,d ['cty'])如何遍历mpg?

[OrderedDict([('', '1'),
          ('manufacturer', 'audi'),
          ('model', 'a4'),
          ('displ', '1.8'),
          ('year', '1999'),
          ('cyl', '4'),
          ('trans', 'auto(l5)'),
          ('drv', 'f'),
          ('cty', '18'),
          ('hwy', '29'),
          ('fl', 'p'),
          ('class', 'compact')]),
OrderedDict([('', '2'),
          ('manufacturer', 'audi'),
          ('model', 'a4'),
          ('displ', '1.8'),
          ('year', '1999'),
          ('cyl', '4'),
          ('trans', 'manual(m5)'),
          ('drv', 'f'),
          ('cty', '21'),
          ('hwy', '29'),
          ('fl', 'p'),
          ('class', 'compact')]),
OrderedDict([('', '3'),
          ('manufacturer', 'audi'),
          ('model', 'a4'),
          ('displ', '2'),
          ('year', '2008'),
          ('cyl', '4'),
          ('trans', 'manual(m6)'),
          ('drv', 'f'),
          ('cty', '20'),
          ('hwy', '31'),
          ('fl', 'p'),
          ('class', 'compact')])]

1 个答案:

答案 0 :(得分:-1)

大致来说,((float(d['cty']) for d in mpg))的for循环等效值为

result = []
for d in mpg:
      result.append(float(d['cy'])

您有mpg的三个元素。第一个有'cty': '18'。因此,当您输入键'cty'时,您将获得值'18',然后将其转换为浮点数18.0。您同样会得到21.020.0。它们的总和是59.0。不过,我看不出如何到达16.68