Search code examples
pythonperformancedictionary

Using map to find the average of nested lists


I am trying to find a concise single line of code that will calculate the mean of each nested list. There will be an input of a two dimensional list of integers and an output float value. The kicker is I am trying to do this with the map() built-in, but am unsure how. Just trying to play around with a couple of things.

Comprehension code:

row_sum = [(sum(idx)/float(len(idx))) for idx in matrix]
return row_sum

Any tips would be greatly appreciated.


Solution

  • If you're intended on using map, this should work

    row_sum = list(map(lambda idx: sum(idx)/float(len(idx)), matrix))