我试图通过将参数传递给键使用的函数来使用字典,例如:
def myfunc(myval):
print(myval)
mydict = {'key1':myfunc(a)}
mydict['key1'] = myfunc(2)
第 7 行,在 mydict = {'key1':myfunc(a)} NameError:名称“a”未定义
它是如何制作的?
最佳答案
mydict = {'key1':myfunc}
mydict['key1'](2) # or any other argument
所以只需在字典中定义函数
关于Python字典将参数传递到函数中用作值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50130712/