Skip to content Skip to sidebar Skip to footer

The Sum() Function Seems To Be Messing Map Objects

I'm doing this code excercise for trying out functional programming in python, and I ran into problems with sum(), list(), and map objects. I don't understand what I'm doing wrong,

Solution 1:

Actually, calling list does change your map object. map is an iterator, not a data structure (in Python3). After it has been looped over once, it is exhausted. To reproduce the result, you need to recreate the map object.

In your case, what you probably want to do is create a list from the map to store the result, then perform the sum.

heights = list(heights)
average = sum(heights) / len(heights)

Edit: another approach.

You can calculate arithmetic mean (and other statistics) directly from iterators using the statistics module. Check out the docs.


Solution 2:

You can create a list by iterating over your map structure to avoid exhausting the iterator with every list call:

people = [{'name': 'Mary', 'height': 160},
      {'name': 'Isla', 'height': 80},
      {'name': 'Sam'}]

heights = [i for i in map(lambda x: x['height'], filter(lambda x: 'height' in x, people))]
average_height = sum(heights)/len(heights)

Output:

120.0

Post a Comment for "The Sum() Function Seems To Be Messing Map Objects"