gpt4 book ai didi

python - 具有将任何函数应用于参数的方法的类?

转载 作者:行者123 更新时间:2023-12-01 03:29:39 25 4
gpt4 key购买 nike

我需要一个带有 mmmethod 的类,该类采用函数作为参数并将该函数应用于列表的每个元素

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]

最佳答案

即使作为参数传递,也可以正常调用该函数。我会在 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,因此它比列表推导式更少使用)

关于python - 具有将任何函数应用于参数的方法的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41069101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com