【问题标题】:Why can I not call this function using a variable as an argument in Python?为什么我不能在 Python 中使用变量作为参数调用此函数?
【发布时间】:2019-03-10 02:02:24
【问题描述】:

例子:

def somerando(a,b,c,d):
    if not a+b+c+d == 9000:
        return (a+b+c+d)

somerando(1,2,3,4)

返回:10

但是

randonumbs = [1,2,3,4]

somerando(randonumbs)

给出以下错误:

TypeError Traceback(最近调用 最后)在 ----> 1 somerando(随机数)

TypeError: somerando() 缺少 3 个必需的位置参数:'b', “c”和“d”

【问题讨论】:

    标签: python


    【解决方案1】:

    您的函数需要 4 个参数。 randonumbs = [1,2,3,4] 是一个列表(四项);这是你的函数的一个参数。

    你可以这样做:

    randonumbs = [1,2,3,4]
    somerando(*randonumbs)
    

    星号 (*) 的这种用法在in this questionPEP 3132 中讨论。

    【讨论】:

      【解决方案2】:

      您将 randonumbs 作为列表传递,这意味着 整个列表被视为函数 somerando 的第一个参数
      您可以使用 somerando(*randonumbs)

      这里,* 表示作为 tuple 传递,** 表示如果在函数参数/参数中使用 **,则作为 dictionary(键、值对)传递。


      谢谢。

      【讨论】:

        【解决方案3】:

        *args 的单星号形式可用作参数,向函数发送非关键字变长参数列表,如下所示

        randonumbs = [1,2,3,4]
        somerando(*randonumbs)
        

        **kwargs 的双星号形式用于将带关键字的可变长度参数字典传递给函数。

        randonumbs = {'a':1, 'b':2, 'c': 3, 'd': 4}
        somerando(**randonumbs)
        

        【讨论】:

          猜你喜欢
          • 2015-05-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-03-02
          • 1970-01-01
          相关资源
          最近更新 更多