使用Python中的相同键多次调用字典函数

时间:2022-11-10 18:03:06

I am having the following dictionary:

我有以下字典:

def func1(a):
  return a

dic = {
       'a' : (lambda: fucn1(2))
      }

I want to call func1 multiple times with different arguments using the same key.

我想使用相同的键使用不同的参数多次调用func1。

dic = {
        'a' : (lambda: func1(2), lambda: func1(4))
      }

So the output is:

所以输出是:

2
4

How can I achieve this? Thank you.

我怎样才能做到这一点?谢谢。

3 个解决方案

#1


0  

I think, it does what you want! No need of lambda functions here. Just call the functions required. Try running it.

我想,它做你想要的!这里不需要lambda函数。只需调用所需的功能即可。尝试运行它。

def func1(a):
  return a

dic = {
   'a' : (func1(2),func1(4))
}
for i in dic:
    for j in dic[i]:
        print j

Output:

2
4

#2


0  

I guess you do not need a lambda:

我想你不需要lambda:

dic = {'a':tuple(func(i) for i in range(4))}
>>> dic
{'a': (0, 1, 2, 3)}

#3


0  

You can use map : map(function_to_apply, list_of_inputs)

你可以使用map:map(function_to_apply,list_of_inputs)

squared = list(map(func1, items))

Or with dict :

或者用dict:

squared ={'a': (map(func1, items))}

input :

items = [1, 2, 3, 4, 5]

Output :

[1, 2, 3, 4, 5]

#1


0  

I think, it does what you want! No need of lambda functions here. Just call the functions required. Try running it.

我想,它做你想要的!这里不需要lambda函数。只需调用所需的功能即可。尝试运行它。

def func1(a):
  return a

dic = {
   'a' : (func1(2),func1(4))
}
for i in dic:
    for j in dic[i]:
        print j

Output:

2
4

#2


0  

I guess you do not need a lambda:

我想你不需要lambda:

dic = {'a':tuple(func(i) for i in range(4))}
>>> dic
{'a': (0, 1, 2, 3)}

#3


0  

You can use map : map(function_to_apply, list_of_inputs)

你可以使用map:map(function_to_apply,list_of_inputs)

squared = list(map(func1, items))

Or with dict :

或者用dict:

squared ={'a': (map(func1, items))}

input :

items = [1, 2, 3, 4, 5]

Output :

[1, 2, 3, 4, 5]