Skip to main content
 首页 » 编程设计

python之如何为函数中的参数赋予类型

2025年05月04日15xxx_UU

我正在尝试制作一个将列表缩短为只有 4 个元素的函数。但是,我无法为函数的参数分配类型,我称之为 my_list。

我尝试使用 type(),但没有用。

这是一些代码:

LL = [2,3,4,5,6,2,5,4] 
print(len(LL)) 
def remove_last_elements(the_list): 
 
    the_list.type(list) #Here it gives an error message that I will put below 
 
    for i in range (len(the_list)-4): 
        the_list=the_list.remove(the_list[len(the_list)-1]) 
remove_last_elements(LL) 
print(LL) 

它给了我这个错误信息。如果我使用 .type()。

    remove_last_elements(LL) 
  File "C:\Users\visha\OneDrive\Desktop\Arnav's Things\Coding\Python Programs (and side-products)\Balloons.py", line 5, in remove_last_elements 
    the_list.type(list) 
AttributeError: 'list' object has no attribute 'type' 

这是另一段没有 .type() 的代码:

LL = [2,3,4,5,6,2,5,4] 
print(len(LL)) 
def remove_last_elements(the_list): 
    for i in range (len(the_list)-4): 
        the_list=the_list.remove(the_list[len(the_list)-1]) 
remove_last_elements(LL) 
print(LL) 

给出以下错误信息:

  remove_last_elements(LL) 
  File "C:\Users\visha\OneDrive\Desktop\Arnav's Things\Coding\Python Programs (and side-products)\Balloons.py", line 5, in remove_last_elements 
    the_list=the_list.remove(the_list[len(the_list)-1]) 
AttributeError: 'NoneType' object has no attribute 'remove' 

请您参考如下方法:

我不确定您通过“向列表分配类型”试图做什么。根据定义,列表属于列表类型,您可以使用 type(the_list) 对其进行验证。不过,我不建议根据此结果做出任何编程决策。假设一切都是正确的类型,如果不正确就崩溃。

如果不确定对象上是否存在某个方法以及要查看哪些方法存在,您可以使用 dir():

>>> dir(list) 
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__ 
', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash_ 
_', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul_ 
_', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmu 
l__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 
 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort' 
] 
>>> "type" in dir(list) 
False 
>>> 

其次,list.remove() 是一个操作 in place 的函数并返回值 None。当您分配(本质上)the_list = None 时,在下一次迭代调用(本质上)None.remove() 会引发您遇到的第二个异常。

解决这两个错误会产生:

LL = [2,3,4,5,6,2,5,4] 
 
def remove_last_elements(the_list): 
    for i in range (len(the_list)-4): 
        the_list.remove(the_list[len(the_list)-1]) 
 
remove_last_elements(LL) 
print(LL) 

现在,这个功能还有必要吗?出于某些原因,我认为不会。

首先,它hardcodes值 4 而不通知调用者,这使得它几乎无法用于其他目的。例如,如果我想删除 5 个元素,我就不走运了,必须编写一个新函数。如果缩短大小是此函数的参数,我更愿意指定列表缩短我自己选择的任意 n 值。

其次,remove 总是删除列表中第一个出现的项目。您的结果列表 [2, 3, 6, 2] 与服务相关,函数名称暗示“删除最后一个元素”。作为您函数的用户,我很惊讶列表中最后 4 个元素中的两个仍然存在!

作为最后的评论,.remove 是一个非常慢的操作:对于列表中的每个项目,我们必须遍历整个列表以找到并删除它。这将对大型列表产生严重的性能影响。

我会使用 Python 的 slice operator高效、简洁和可预测地执行列表缩短:

>>> LL = [2,3,4,5,6,2,5,4] 
>>> LL[:-4] # remove and return up to the last 4 
[2, 3, 4, 5] 
>>> LL[-4:] # remove and return the last 4 
[6, 2, 5, 4] 

您可以修改您的程序以使用它,如下所示:

LL = [2,3,4,5,6,2,5,4] 
 
LL = LL[:-4] 
print(LL) # => [2, 3, 4, 5]