如何使用 map 计算具有多个参数的函数
How to use map to calculate a function with more than one parameter
.我有一个分类器函数:
def f(x, threshold):
if logi == 1:
if x > threshold:
return 1
else:
return 0
并且有一个列表 a=[2, 3, 12, 4, 53, 3],如果使用 map(f(threshold=4),a) 将引发错误 "f() missing 1 required positional argument: 'x'"
但如果我指定阈值默认值 4,它将起作用。修改函数定义为
def f(x, threshold=4):
if logi == 1:
if x > threshold:
return 1
else:
return 0
map(f,a)
会有预期的结果[0, 0, 1, 0, 1, 0],我想知道是否有一些方法可以在不指定参数默认值的情况下达到相同的目标?
i would like to know if there is some method can reach the same goal
without specify parameter default? thanks in advance!
确实有!,确实有几种方法。
就我个人而言,我会使用列表理解,因为它们可读性很强。像这样:
def f(x, threshold, logi=1):
if logi == 1:
if x > threshold:
return 1
else:
return 0
else:
if x < threshold:
return 1
else:
return 0
a=[2, 3, 12, 4, 53, 3]
x = [f(item, 4) for item in a]
print(x)
#output => [0, 0, 1, 0, 1, 0]
希望这对您有所帮助:)
如果您设置在地图上,那么 functools 可能会有所帮助:
from functools import partial
mapfunc = partial(f, 4)
(map(mapfunc, a))
map
支持接受多个迭代器,当最短的迭代器耗尽时停止,将每个迭代器的输出作为连续的位置参数传递给映射器函数。如果你有一个固定的参数,你可以使用 itertools.repeat
一遍又一遍地产生它,例如:
from itertools import repeat
map(f, a, repeat(4))
这种方法可以推广到更复杂的场景,允许循环一组固定值 (itertools.cycle
),或者像 zip
那样将两个可迭代对象配对,但不需要 zip
然后 itertools.starmap
元组返回到位置参数。
另一种对常量参数特别有用的方法是部分绑定 functools.partial
:
from functools import partial
map(partial(f, threshold=4), a)
其中 partial
创建一个新的(CPython 中的 C 级)包装函数,它将在未明确覆盖时将提供的参数传递给包装函数。
.我有一个分类器函数:
def f(x, threshold):
if logi == 1:
if x > threshold:
return 1
else:
return 0
并且有一个列表 a=[2, 3, 12, 4, 53, 3],如果使用 map(f(threshold=4),a) 将引发错误 "f() missing 1 required positional argument: 'x'" 但如果我指定阈值默认值 4,它将起作用。修改函数定义为
def f(x, threshold=4):
if logi == 1:
if x > threshold:
return 1
else:
return 0
map(f,a)
会有预期的结果[0, 0, 1, 0, 1, 0],我想知道是否有一些方法可以在不指定参数默认值的情况下达到相同的目标?
i would like to know if there is some method can reach the same goal without specify parameter default? thanks in advance!
确实有!,确实有几种方法。 就我个人而言,我会使用列表理解,因为它们可读性很强。像这样:
def f(x, threshold, logi=1):
if logi == 1:
if x > threshold:
return 1
else:
return 0
else:
if x < threshold:
return 1
else:
return 0
a=[2, 3, 12, 4, 53, 3]
x = [f(item, 4) for item in a]
print(x)
#output => [0, 0, 1, 0, 1, 0]
希望这对您有所帮助:)
如果您设置在地图上,那么 functools 可能会有所帮助:
from functools import partial
mapfunc = partial(f, 4)
(map(mapfunc, a))
map
支持接受多个迭代器,当最短的迭代器耗尽时停止,将每个迭代器的输出作为连续的位置参数传递给映射器函数。如果你有一个固定的参数,你可以使用 itertools.repeat
一遍又一遍地产生它,例如:
from itertools import repeat
map(f, a, repeat(4))
这种方法可以推广到更复杂的场景,允许循环一组固定值 (itertools.cycle
),或者像 zip
那样将两个可迭代对象配对,但不需要 zip
然后 itertools.starmap
元组返回到位置参数。
另一种对常量参数特别有用的方法是部分绑定 functools.partial
:
from functools import partial
map(partial(f, threshold=4), a)
其中 partial
创建一个新的(CPython 中的 C 级)包装函数,它将在未明确覆盖时将提供的参数传递给包装函数。