Using map in Python -
i'm trying use map
python function (i know can use list comprehension instructed use map in example) take row average of 2 row matrix.
here think answer should like:
def average_rows2(mat): print( map( float(sum) / len , [mat[0],mat[1]] ) ) average_rows2([[4, 5, 2, 8], [3, 9, 6, 7]])
right now, sum function works:
def average_rows2(mat): print( map( sum , [mat[0],mat[1]] ) ) average_rows2([[4, 5, 2, 8], [3, 9, 6, 7]])
the first problem adding float()
sum function gives error:
typeerror: float() argument must string or number
which weird because elements of resulting list should integers since calculates sum.
also, adding / len
sum function gives error:
typeerror: unsupported operand type(s) /: 'builtin_function_or_method' , 'builtin_function_or_method'
for error, tried *
, //
, says none supported operand types. don't understand why none of these supported.
maybe means map
function doesn't take composite functions?
the first argument has evaluated before can passed map
. this:
float(sum) / len
is causing various errors doesn't make sense evaluate on own (unless you'd shadowed sum
, len
, different problem). trying sum on 1 built-in function divide another! therefore cannot argument.
instead, make function, e.g.:
lambda lst: float(sum(lst)) / len(lst)
this callable single argument, therefore can used first argument map
, apply each element in second argument. use regular function, rather anonymous lambda
(as shown in https://stackoverflow.com/a/34831192/3001761).
Comments
Post a Comment