字典整数作为键,函数作为值?

2024-10-02 22:27:09 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码:

def test1():
  print("nr1")

def test2():
  print("nr2")

def test3():
  print("nr3")

def main():
  dictionary = { 1: test1(), 2: test2(), 3: test3() }
  dictionary[2]

if __name__ == "__main__":
  main()

此代码返回:

^{pr2}$

我需要在代码中做什么更改才能得到:

nr2

我使用的是python2.7.13。在


Tags: 代码namedictionaryifmaindefprinttest1
3条回答

下面的行实际调用每个函数并将结果存储在字典中:

dictionary = { 1: test1(), 2: test2(), 3: test3() }

这就是为什么会看到三行输出。正在调用每个函数。因为函数没有返回值,所以值None存储在字典中。打印(print(dictionary):

^{pr2}$

相反,将函数本身存储在字典中:

dictionary = { 1: test1, 2: test2, 3: test3 }

print(dictionary)的结果:

{1: <function test1 at 0x000000000634D488>, 2: <function test2 at 0x000000000634D510>, 3: <function test3 at 0x000000000634D598>}

然后使用字典查找来获取函数,然后调用它:

dictionary[2]()

创建字典时省略函数调用,只调用dictionary[2]返回的内容:

def main():
  dictionary = { 1: test1, 2: test2, 3: test3 }
  dictionary[2]()

不要调用dict内部的函数;调用dict查找的结果。在

dictionary = { 1: test1, 2: test2, 3: test3 }
dictionary[2]()

相关问题 更多 >