【问题标题】:can functions be executed directly in dictionary in python rather than putting only a call to function in dictionary?函数可以直接在python中的字典中执行,而不是只在字典中调用函数吗?
【发布时间】:2020-07-03 07:59:43
【问题描述】:

当尝试在字典中实现 switch-case 语句时,我尝试了以下代码

if __name__ == '__main__':
N = int(input())
lst=[]
dict={
    'insert' : lst.insert,
    'print' : print(lst),
    'remove' : lst.remove,
    'append' : lst.append,
    'sort' : lst.sort,
    'pop' : lst.pop,
    'reverse' : lst.reverse
}   
for _ in range(N) :
     key,*args=input().split()
     args=list(map(int,args))
     if key in dict :
        dict[key](*args)
     else :
        continue

我得到的输出

5              //value i gave to N
[]
insert 0 5
append 5
print
Traceback (most recent call last):
  File "p1.py", line 17, in <module>
    dict[key](*args)
TypeError: 'NoneType' object is not callable

所以我认为我们只能调用字典中的函数所以我尝试了

def insert(i,e):
    lst.insert(i,e)

def prin() :
    print(lst)

def rem(e):
    lst.remove(e)

def append(e):
    lst.append(e)

def sort():
    lst.sort()

def pop():
    lst.pop()

def reverse():
    lst.reverse()

N=int(input())
lst=[]
switch={
'insert' : insert,
'print' : prin,
'remove' : rem,
'append' : append,
'sort' : sort,
'pop' : pop,
'reverse' : reverse
}
for _ in range(N) :
    key,*args=input().split()
    args=list(map(int,args))

    if key in switch :
        switch[key](*args)
    else :
        continue    

它工作正常

我的疑问是代码错误,为什么字典中的打印语句直接执行并打印空列表[]

【问题讨论】:

  • 使用字典没有实现 swtich 语句。在任何情况下,当您使用 print(lst) 您正在那里调用打印函数
  • 在第一个代码中,您打印空列表并将返回值 None 放入字典中。您实际上只需要更改那个,而不是全部:'print': lambda: print(lst)。

标签: python python-3.x dictionary


【解决方案1】:

您可以在第一个代码 sn-p 中了解导致错误的语法差异,让我们在这里看看:

'insert': lst.insert,
'print' : print(lst),

现在在您重新定义它时使用的第二个代码:

def insert(i,e):
    lst.insert(i,e)

def prin() :
    print(lst)

你能看出括号中的区别以及你是如何传递参数的吗? 请记住,当您使用函数作为参数时,它们是可以引用和调用的第一类对象。在您的第一次尝试中,您首先调用函数 print(lst) 并将其结果用作参数,即一个空列表。您不需要修改所有代码,只需不要像使用其他函数一样调用 print 并传递参数。

【讨论】:

    猜你喜欢
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    相关资源
    最近更新 更多