gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:15:34 27 4
gpt4 key购买 nike

我有一个来自 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

关于python - 传递列表并将其长度设置为python中的默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48301468/

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