我需要一个带有mmeod的类,它接受一个函数作为参数,并将该函数应用于列表的每个元素
class matrix:
def __init__(self,xs):
self.xs=xs #xs is a list
def map(self,function): ??? I don't know how to implent this one
结果应该是
v = matrix([1, 2, 3])
r = v.map(sqrt)
print(r)
matrix [1.0, 1.41, 1.73]
答案 0 :(得分:2)
即使作为参数传递,也可以正常调用该函数。我会在self.xs
:
from math import sqrt
class matrix:
def __init__(self,xs):
self.xs=xs #xs is a list
def map(self,function):
return [function(x) for x in self.xs]
v = matrix([1, 2, 3])
r = v.map(sqrt)
print(r)
结果:
[1.0, 1.4142135623730951, 1.7320508075688772]
不提及对象和类,请注意内置map
几乎可以满足您的要求,值得一提,因为您在猜测中提到了名称:
list(map(sqrt,[1, 2, 3]))
(自Python 3以来需要转换为list
,所以它比列表推导更少使用)