Python 如何使用map计算具有多个参数的函数
.我有一个分类器功能:Python 如何使用map计算具有多个参数的函数,python,python-3.x,mapreduce,Python,Python 3.x,Mapreduce,.我有一个分类器功能: 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()缺少1个必需的位置参数:'x'” 但如果我指定默认阈值4,它将工作。将函数定义修改为 def f(x, threshold=4): if logi =
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()缺少1个必需的位置参数:'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],我想知道是否有一些方法可以在不指定默认参数的情况下达到相同的目标
我想知道是否有一些方法可以达到同样的目标
没有指定参数默认值?提前谢谢
当然有!,真的有一些方法。
就我个人而言,我会使用列表理解,因为它们可读性很强。像这样:
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]
map
支持接受多个iterable,当最短的iterable用完时停止,并将每个iterable的输出作为顺序位置参数传递给mapper函数。如果只有一个固定参数,可以使用itertools。重复反复生成它,例如:
from itertools import repeat
map(f, a, repeat(4))
这种方法可以推广到更复杂的场景,允许循环一组固定的值(itertools.cycle
),或者只将两个iterable与zip
配对,但不需要zip
,然后itertools.starmap
将元组返回到位置参数
另一种对常量参数特别有用的方法是使用functools进行部分绑定。部分
:
from functools import partial
map(partial(f, threshold=4), a)
其中partial
创建一个新的(CPython中的C级)包装函数,当未显式重写时,该函数会将提供的参数传递给包装函数。是否有使用函数映射来访问gold的方法?@martin也许functools-partial是您要寻找的,导入可以吗?
from functools import partial
map(partial(f, threshold=4), a)