如何在具有多个参数的函数上使用python Maps

问题描述 投票:0回答:1
NAME_LIST = ["abc1","abc2","cde1"]
class abc:
    @staticmethod
    def foo(a,name,*args):
         a = do_something(name,*args)
         return do_another(a)

[当有多个函数参数时,如何使用python映射传递名称列表并打印输出

类似这样,我想将a,* args保留为常量(但不想使其成为默认参数)

list(map(abc.foo, NAME_LIST))

我想将NAME_LIST变量传递给name

python python-3.x functools
1个回答
0
投票

您可以做什么:

def myFunc(x,y, *args):
    return x*y+sum(args)

x=[[1,4,5,5,6,7], [3,2,1], [7,8], [2,9,0,4,3]]

y=list(map(lambda a: myFunc(*a), x))

y

#outputs:
[27, 7, 56, 25]

所以在您的情况下:

NAME_LIST = ["abc1","abc2","cde1"]
class abc:
    @staticmethod
    def foo(a,name,*args):
         a = do_something(name,*args)
         return do_another(a)

list(map(lambda x: abc.foo(*x), [NAME_LIST]))

只是注释map会在提供的可迭代范围内进行迭代,因此它将使用传递列表的每个元素来执行您的函数,如果将其保留为NAME_LIST,则每次都会是一个字符串-因此您的函数将失败,因为它有2个位置参数,所以这是要对列表执行map的列表的每个元素的最小大小-因此[NAME_LIST]

希望这很有道理!

© www.soinside.com 2019 - 2024. All rights reserved.