我是python的初学者。我有一个代码,但我只能理解其中的一部分。您能解释一下最后一个针对此问题调用命令的行吗?还要为什么我们将li:list作为参数传递给pop()函数?
def insert(ls,params):
ls.insert(int(params[0]), int(params[1]))
def print_list(ls, params):
print(ls)
def remove(ls, params):
ls.remove(int(params[0]))
def append(ls, params):
ls.append(int(params[0]))
def sort_list(ls, params):
ls.sort()
def pop(ls: list, params):
ls.pop()
def reverse(ls, params):
ls.reverse()
commands = {
'insert': insert,
'print': print_list,
'remove': remove,
'append': append,
'sort': sort_list,
'pop': pop,
'reverse': reverse
}
if __name__ == '__main__':
N = int(input())
ls = []
for _ in range(N):
cmd = input().split(' ')
commands[cmd[0]](ls, cmd[1:])
Oof,好的,让我们开始吧。首先,我说这不是惯用的代码,也不是任何熟练的Python程序员构造程序的方式。就是说:分析它是有好处的。
向后工作:让我们谈谈
我们为什么将li:list作为参数传递给pop()函数
您正在说的是这里的函数声明
def pop(ls: list, params):
ls.pop()
被称为功能注释,并记录在here中。它们通常用作类型提示,Python运行时将其完全剥离。使用或省略功能注释不会改变任何行为。
现在是肉和土豆:
你能解释一下最后一行吗?>
cmd = input().split(' ') commands[cmd[0]](ls, cmd[1:])
这两行是分不开的。第一个调用input
询问用户要运行的内容,然后将其拆分为空格以生成字符串列表。例如,可能是:
# user-input: append 3 4 5 6 7 cmd == ['append', '3', '4', '5', '6', '7']
然后,下一行将获取该列表的第一个元素,并以该名称查找该命令,这是一个函数
commands[cmd[0]]
并调用它,将列表本身以及来自用户输入的其余参数作为参数传入
(ls, cmd[1:])
在我的示例中,这导致呼叫看起来像:
append(lst, ['3', '4', '5', '6', '7'])
如果我要重写此内容,我会质疑它是否完全相关。似乎许多内部组件正在向用户公开。如果确信有必要,我将使用
list.__getattribute__
将方法名称与那些方法配对。
# replacing all the function definitions and the "commands" dict: def get_method(lst: list, attrname: str): try: method = lst.__getattribute__(attrname) except AttributeError: return None
然后从内联参数中拆分命令名称,并在调用该方法之前检查该方法是否存在。
if __name__ == '__main__':
n = int(input())
lst = []
for _ in range(n):
cmd, *args = input().split(' ')
method = get_method(lst, cmd)
if method is not None:
method(*args)