Skip to main content
 首页 » 编程设计

python之传递列表并将其长度设置为python中的默认参数

2025年05月04日10小虾米

我有一个来自 Python 的类方法,如下所示:

def func(indel, nind=indel.length): 
    #do_something 

indel 是一个列表。

我在使用这个函数定义时遇到错误。有什么办法可以做到吗?

请您参考如下方法:

虽然我想知道你为什么要使用参数,但你可能想要这样做,因为传递列表的长度是可选的,例如如果你想对列表的一小部分进行操作.如果是这样,这就是我将使用的代码:

def func(indel, length = None): 
    #do_something 
    if length is None: # By default, use the length of the list 
        length = len(indel) 
    # do whatever with indel and length 
 
# test methods 
test = [1, 2, 3, 4, 5] 
 
func(test) # in this case, length = 5 
 
func(test, 1) # in this case, length = 1