【问题标题】:Assigning length of a list in the parameters of a function在函数的参数中分配列表的长度
【发布时间】:2016-05-30 18:59:06
【问题描述】:

所以我想在我的函数中将列表的长度设置为一个变量,但它说我的列表没有定义:

def maxElement(list, start=0, end = len(serie)):
    return max(serie[start:end])

serie = [9, 3, 6, 1, 7, 5, 4, 8, 2]
print maxElement(serie)

【问题讨论】:

  • maxElement的签名中调用len函数会失败,因为serie还没有定义。但更好的问题是,你为什么要这样做?您的列表作为参数传递,因此请在您的函数中调用 len(list) 以了解其长度。
  • 顺便说一句,不要使用 list 作为变量名,因为它会影响内置的 list 类型。

标签: python function parameters arguments


【解决方案1】:

在您定义函数时,serie 尚未定义。此外,在模块加载时评估和绑定默认参数,而不是在调用函数时。因此,您不能引用 maxElement(lst, start=0, end=len(lst)) 或任何其他动态运行时相关默认值的另一个参数:

def maxElement(lst, start=0, end=None):  # don't shadow built-in name list
    if end is None:
        end = len(lst)
    return max(lst[start:end])  # do not use serie here, but lst

> serie = [9, 3, 6, 1, 7, 5, 4, 8, 2]
> print maxElement(serie)
9

> print maxElement(serie, start=1, end=6)
7

【讨论】:

    【解决方案2】:

    您的代码存在几个问题。

    首先,您实际上并没有使用函数的list 参数。相反,您使用的是全局列表serie。顺便说一句,你不应该使用 list 作为变量名,因为它会隐藏(覆盖)内置的 list 类型,这可能会导致神秘的错误。

    正如 schwobaseggl 所提到的,默认函数参数是在定义函数时评估的,而不是在调用它时。因此,当您执行end = len(serie) 时,将end 设置为定义函数时serie 的当前长度。但是,您的脚本在定义 maxElement 之后定义了 serie,因此尚未定义该名称,这就是您收到此错误的原因:

    NameError: name 'serie' is not defined
    

    如果您将serie 的定义放在之前 maxElement 的定义将消除该错误,但由于我已经提到的错误,该功能仍然无法正常工作.

    实际上,可能是另一个错误。 看起来您想要搜索介于 startend 之间的最大元素,包括在内。如果是这样,您需要使用lst[start:end+1] 之类的东西。如果你想使用正常的 Python 约定,其中end 被排除在范围之外,那么你可以只使用lst[start:end]。请注意,切片的结束索引是否超出列表无关紧要;对于n > 0,lst[start:len(lst)+n]lst[start:len(lst)] 完全相同。

    这是您的代码的修复版本。我稍微修改了数据以使其更易于测试。

    def max_element(lst, start=0, end=None):
        if end is None:
            end = len(lst)
        return max(lst[start:end + 1])
    
    serie = [0, 3, 6, 1, 7, 5, 4, 8, 2]
    
    print serie
    print max_element(serie)
    print max_element(serie, start=4)
    print max_element(serie, end=2)
    print max_element(serie, start=4, end=6)
    print max_element(serie, start=3, end=3)
    

    输出

    [0, 3, 6, 1, 7, 5, 4, 8, 2]
    8
    8
    6
    7
    1
    

    然而,这个功能并不是必须的。你应该直接在你的列表上调用max,如果需要的话,切片,例如:

    print max(serie[4:7])
    

    【讨论】:

    • 相当全面的解释!但是为什么在切片中使用end + 1 而不仅仅是end更新: 毕竟最后一个列表索引是len(lst)-1 反正..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-02
    • 2011-11-27
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 2012-01-06
    • 1970-01-01
    相关资源
    最近更新 更多