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

output: 16.86

how does the d['cty']) loop through mpg as we are dealing with a list and get value corresponding to it?

[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')])]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • I'm not sure what answer you are looking for aside from "that's how generator expressions work". – chepner Jul 18 '19 at 19:09
  • can you explain how this is written in regular for loop, am not getting how d['cty'] can get the 18 20 21 – sai srikar Jul 18 '19 at 19:19
  • 1
    D loops through mpg. Cty is a key. In "regular" it would be: `sum = 0 for d in mpg: sum += d['ctg'] print(float(sum)/ len(mpg))` – Mr. Radical Jul 18 '19 at 19:42

2 Answers2

0

It calculates average of all elements, not only for 3 values of cty but 234 list values of 'cty' and then divides from its length of a list.

Put 'cty' in a variable and print like this

ct =list(float(d['cty']) for d in mpg) print (ct)

You'll understand.

sum(float(d['cty']) for d in mpg) if you run this only you'll get a sum 3945.00 and when you divide by length of list from 234, you'll get ans as 16.86

-1

Roughly speaking, the for-loop equivalent of ((float(d['cty']) for d in mpg)) would be

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

You have three elements of mpg. The first one has 'cty': '18'. So when you feed in the key 'cty', you get the value '18', which is then converted to the float 18.0. You similarly get 21.0 and 20.0. The sum of those is 59.0. I don't see how that gets to 16.68, though.

Acccumulation
  • 3,491
  • 1
  • 8
  • 12