The sum() function seems to be messing map objects

前端 未结 2 1223
庸人自扰
庸人自扰 2021-01-28 14:58

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

2条回答
  •  余生分开走
    2021-01-28 15:30

    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.

提交回复
热议问题