gpt4 book ai didi

python - 将参数传递给python中字典调用的函数

转载 作者:太空宇宙 更新时间:2023-11-04 04:36:33 26 4
gpt4 key购买 nike

我是 python 和实现堆栈的新手。我正在使用字典调用堆栈函数。但是,push() 要求我传递一个参数。我该怎么做?

class stack():

def __init__(self):
self.items = []

def push(self,item):
self.items.append(item)

def pop(self):
return self.items.pop()

def isEmpty(self):
return self.items == []

def getStack(self):
return print(self.items)

s = stack()
switcher = {
'1' : s.push,
'2' : s.pop,
'3' : s.isEmpty,
'4' : s.getStack,
}

def dictionaryCall(key):
switcher[key]()

while(1):
key = input('enter choice 1.push 2. pop 3.isEmpty 4 getStack 5.exit: ')
if key == '5':
break
dictionaryCall(key)

最佳答案

这是一个有效的实现。如您所见,您必须向 dictionaryCall 添加一个可选的第二个参数(此处称为 element),然后将其传递给选定的方法。

class stack():

def __init__(self):
self.items = []

def push(self,item):
self.items.append(item)

def pop(self):
print(self.items.pop())

def isEmpty(self):
# I dropped the `return` here due to syntax error
print (self.items == [])

def getStack(self):
# I dropped the `return` here due to syntax error
print (self.items)

s = stack()
switcher = {
'1' : s.push,
'2' : s.pop,
'3' : s.isEmpty,
'4' : s.getStack,
}

# I added an optional parameter for the `push` method
def dictionaryCall(key, element = None):
method = switcher[key]

# call the method with element if it exists
if element == None: method()
else: method(element)

# call from command line
if __name__ == '__main__':
while(1):
key = input('enter choice 1.push 2. pop 3.isEmpty 4 getStack 5.exit: ')
if key == '5':
break

print ('> {0}'.format(key))

if key == '1':
element = input('enter an element to push onto the stack: ')
dictionaryCall(key, element)
else: dictionaryCall(key)

示例:

enter choice 1.push 2. pop 3.isEmpty 4 getStack 5.exit: '1'
> 1
enter an element to push onto the stack: 'foo'
enter choice 1.push 2. pop 3.isEmpty 4 getStack 5.exit: '3'
> 3
False
enter choice 1.push 2. pop 3.isEmpty 4 getStack 5.exit: '4'
> 4
['foo']
enter choice 1.push 2. pop 3.isEmpty 4 getStack 5.exit:

需要注意的几点:

  • return print (...) 是无效语法(只写 print (...))
  • 通过 input 从命令行读取的参数被评估(这意味着你必须输入例如 '1' 来推送一个元素,因为你的字典有字符串键<
  • 要从命令行运行 python 程序,您需要将其包装在 if __name__ == '__main__': ... 否则文件将被解析但不会执行
  • 正如@Pm2Ring 在评论中所说,pop 应该打印弹出的元素

关于python - 将参数传递给python中字典调用的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51569308/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com