【问题标题】:confused about error using lambda function对使用 lambda 函数的错误感到困惑
【发布时间】:2020-05-12 14:42:34
【问题描述】:
#to add and multiply numbers using lambda in python
a=int(input("a number: "))
b=int(input("another number: "))
print("the sum is {}".format(lambda a,b:a+b))
print("the multiple is {}".format(lambda a,b:a*b))

我尝试使用 lambda 将两个数字相加和相乘,但我不知道为什么它会显示这样的错误。我是编程初学者 错误是:

the sum is <function <lambda> at 0x000001B6BF941B88>
the multiple is <function <lambda> at 0x000001B6BF893798>

【问题讨论】:

  • 因为lambda 是一个函数。你实际上需要调用它来获得一个值......你为什么在这里使用lambda?你可以做 (lambda a,b: a+b)(a,b) 但这只是做 a + b 的笨拙方式...
  • 什么是 lambdas for?只需使用a+ba*b

标签: python python-3.x function lambda


【解决方案1】:

您创建了一个函数,但实际上并没有调用它。您可以通过两种方式进行更改:调用 lambda 或不使用 lambda 函数。在这种情况下,第二个会更好,但如果您只是想了解 lambda 函数,您可以使用第一个。

print("the sum is {}".format((lambda a,b:a+b)(a, b)))
print("the multiple is {}".format((lambda a,b:a*b)(a, b)))

我所做的更改是将 lambda 替换为 (lambda a,b:a+b)(a, b)

或者只是删除 lambda

print("the sum is {}".format(a+b))
print("the multiple is {}".format(a*b))

在这种情况下,这将是更好的选择。

【讨论】:

    【解决方案2】:

    lambda 是写匿名函数的方式,但它们仍然是你需要调用它们的函数。

    a=int(input("a number: "))
    b=int(input("another number: "))
    print("the sum is {}".format((lambda a,b:a+b)(a,b)))
    print("the multiple is {}".format((lambda a,b:a*b)(a,b)))
    

    输出:

    a number: 1
    another number: 2
    the sum is 3
    the multiple is 2
    

    【讨论】:

    • 感谢您的帮助,这是我的第一个堆栈问题,所以我很高兴得到了我没想到的帮助。
    【解决方案3】:

    您的输出没有错误。由于lambda 是一个函数,所以当您打印它时,您会看到&lt;function &lt;lambda&gt; at 0x000001B6BF941B88&gt;

    如果你想调用它,试试:

    a=int(input("a number: "))
    b=int(input("another number: "))
    sum_func = lambda a,b:a+b
    product_func = lambda a,b:a*b
    print("the sum is {}".format(sum_func(a,b)))
    print("the multiple is {}".format(product_func(a,b)))
    
    

    【讨论】:

    • 非常感谢,我现在想到了,我想像这样使用 lambda 已经意味着我调用了 lambda 函数,但我现在明白了。
    • 乐于助人:)
    【解决方案4】:

    尝试将其存储在变量中。

        #to add and multiply numbers using lambda in python
        a=int(input("a number: "))
        b=int(input("another number: "))
        add = lambda a,b:a+b
        mult = lambda a,b:a*b
        print("the sum is {}".format(add(a,b)))
        print("the multiple is {}".format(mult(a,b)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多