【问题标题】:TypeError: takes one positional argument but five were given [closed]TypeError:采用一个位置参数,但给出了五个 [关闭]
【发布时间】:2014-06-01 23:43:22
【问题描述】:
def double_preceding(values):

    '''(list of ints)->None

    Update each value in a list with twice
    the preceding value, and the first item
    with 0.

    For example, if x has the value
    [1,2,3,4,5], after calling the
    double_preceding with argument x,
    x would have the value[0,2,4,6,8]

    >>>double_preceding(2,3,4,5,6)
    [0,4,6,8,10]
    >>>double_preceding(3,1,8,.5,10)
    [0,6,2,16,1] 
    '''
    if values != []:
        temp = values[0]
        values[0] = 0
        for i in range(0, len(values)):
            double = 2 * temp
            temp = values[i]
            values[i] = double
    return #None

那我做错了什么?我在任何地方都没有发现问题,我已经尝试修复了一个小时。

我修复了代码:

def double_preceding(values):

    if values != 0:  
            temp = values[0]
            values[0] = 0
         for i in range(1, len(values)):
               double = 2 * temp
               temp = values[i]
               values[i] = double
    print(values)
    return#None

【问题讨论】:

  • 这是一个非常简洁、明确和清晰的错误信息,不是吗?

标签: python typeerror argument-passing


【解决方案1】:

您的函数只接受一个参数,而您将 5 传递给它。替换:

>>>double_preceding(2,3,4,5,6)
[0,4,6,8,10]
>>>double_preceding(3,1,8,.5,10)
[0,6,2,16,1] 

与:

>>>double_preceding([2,3,4,5,6])
[0,4,6,8,10]
>>>double_preceding([3,1,8,.5,10])
[0,6,2,16,1] 

【讨论】:

  • 我想通了。在这种情况下,我需要添加 print(argument) print(values) 以获得参数的打印输出。谢谢
【解决方案2】:

我很好奇您为什么决定传入列表的文字值而不是传递包含列表的变量。例如。

x = [1, 2, 3, 4, 5]

double_preceding(x)

如果你只是传递它 x 取决于你在函数中的代码,你的函数应该可以工作。您可以发布函数内部的实际代码吗?

【讨论】:

  • 所以我得到了一个可以解决的例子,但是给出的问题和称为“值”的参数我可以使用 x,这很好,但我仍然得到:函数需要 1 个位置参数,但 5 个是给定的。
  • 所以 x 的交易值是任意的。如果 x != []: temp = x[0] x[0] = 0 for i in range(0, len(x)): double = 2 * temp temp = x[i] x[i] = double
猜你喜欢
  • 1970-01-01
  • 2022-12-12
  • 2023-01-11
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
  • 2021-01-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多